Content uploaded by Sudhakar Kumar
Author content
All content in this area was uploaded by Sudhakar Kumar on Aug 14, 2021
Content may be subject to copyright.
Microcontroller Programming
with Arduino and Python
Sudhakar Kumar, Manas Ranjan Das
Rajesh Kushalkar, Nirmala Venkat, Chandrashekhar Gourshete
Kannan M. Moudgalya
FOSSEE Project
Indian Institute of Technology Bombay
June 2021
The soft-copy/electronic-version of this book is released under Creative Commons
Attribution-NonCommercial-NoDerivatives (CC BY-NC-ND) license. Those who
want to use this book for commercial purposes may contact Prof. Kannan Moudgalya.
Contents
List of Figures vii
List of Tables ix
List of Arduino Code xi
List of Python Code xiii
List of Acronyms xv
1 Introduction 1
2 Hardware Environment 3
2.1 Microcontroller .............................. 3
2.1.1 Organization of a Microcontroller . . . . . . . . . . . . . . . . 3
2.1.2 Microcontroller Peripherals . . . . . . . . . . . . . . . . . . . 5
2.2 Open Source Hardware (OSHW) . . . . . . . . . . . . . . . . . . . . 7
2.3 Arduino .................................. 8
2.3.1 BriefHistory ........................... 8
2.3.2 Arduino Uno Board . . . . . . . . . . . . . . . . . . . . . . . 9
2.3.3 Popular Arduino Projects . . . . . . . . . . . . . . . . . . . . 9
2.4 Shield ................................... 11
2.5 Experimental Test Bed . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.6 Doing the Experiments with a Breadboard . . . . . . . . . . . . . . . 13
3 Communication between Software and Arduino 19
3.1 ArduinoIDE ............................... 19
3.1.1 Downloading and installing on Windows . . . . . . . . . . . . 20
3.1.2 Downloading and installing on GNU/Linux Ubuntu . . . . . . 21
3.1.3 Arduino Development Environment . . . . . . . . . . . . . . . 23
iv Contents
3.1.4 Testing Arduino with a sample program . . . . . . . . . . . . 26
3.1.5 FLOSSFirmware......................... 27
3.2 Python................................... 27
3.2.1 Downloading and installing on Windows . . . . . . . . . . . . 28
3.2.2 Downloading and installing on GNU/Linux Ubuntu . . . . . . 30
3.2.3 Python-Arduino toolbox . . . . . . . . . . . . . . . . . . . . . 31
3.2.4 Firmware ............................. 32
4 Interfacing a Light Emitting Diode 35
4.1 Preliminaries ............................... 35
4.2 Connecting an RGB LED with Arduino Uno using a breadboard . . 37
4.3 Lighting the LED from the Arduino IDE . . . . . . . . . . . . . . . . 38
4.3.1 Lighting the LED . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.3.2 ArduinoCode........................... 40
4.4 Lighting the LED from Python . . . . . . . . . . . . . . . . . . . . . 42
4.4.1 Lighting the LED . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.4.2 PythonCode ........................... 44
5 Interfacing a Pushbutton 49
5.1 Preliminaries ............................... 49
5.2 Connecting a pushbutton with Arduino Uno using a breadboard . . . 49
5.3 Reading the pushbutton status from the Arduino IDE . . . . . . . . 52
5.3.1 Reading the pushbutton status . . . . . . . . . . . . . . . . . 52
5.3.2 ArduinoCode........................... 53
5.4 Reading the pushbutton status from Python . . . . . . . . . . . . . . 54
5.4.1 Reading the pushbutton status . . . . . . . . . . . . . . . . . 54
5.4.2 PythonCode ........................... 55
6 Interfacing a Light Dependent Resistor 59
6.1 Preliminaries ............................... 59
6.2 Connecting an LDR with Arduino Uno using a breadboard . . . . . 61
6.3 Interfacing the LDR through the Arduino IDE . . . . . . . . . . . . 62
6.3.1 Interfacing the LDR . . . . . . . . . . . . . . . . . . . . . . . 62
6.3.2 ArduinoCode........................... 64
6.4 Interfacing the LDR through Python . . . . . . . . . . . . . . . . . . 64
6.4.1 Interfacing the LDR . . . . . . . . . . . . . . . . . . . . . . . 64
6.4.2 PythonCode ........................... 66
Contents v
7 Interfacing a Potentiometer 69
7.1 Preliminaries ............................... 69
7.2 Connecting a potentiometer with Arduino Uno using a breadboard . 70
7.3 Reading the potentiometer from the Arduino IDE . . . . . . . . . . . 71
7.3.1 Reading the potentiometer . . . . . . . . . . . . . . . . . . . . 71
7.3.2 ArduinoCode........................... 72
7.4 Reading the potentiometer from Python . . . . . . . . . . . . . . . . 73
7.4.1 Reading the potentiometer . . . . . . . . . . . . . . . . . . . . 73
7.4.2 PythonCode ........................... 74
8 Interfacing a Thermistor 77
8.1 Preliminaries ............................... 77
8.2 Connecting a thermistor with Arduino Uno using a breadboard . . . 79
8.3 Interfacing the thermistor from the Arduino IDE . . . . . . . . . . . 80
8.3.1 Interfacing the thermistor . . . . . . . . . . . . . . . . . . . . 80
8.3.2 ArduinoCode........................... 82
8.4 Interfacing the thermistor from Python . . . . . . . . . . . . . . . . . 84
8.4.1 Interfacing the thermistor . . . . . . . . . . . . . . . . . . . . 84
8.4.2 PythonCode ........................... 85
9 Interfacing a Servomotor 89
9.1 Preliminaries ............................... 89
9.2 Connecting a servomotor with Arduino Uno using a breadboard . . . 90
9.3 Controlling the servomotor through the Arduino IDE . . . . . . . . . 91
9.3.1 Controlling the servomotor . . . . . . . . . . . . . . . . . . . 91
9.3.2 ArduinoCode........................... 94
9.4 Controlling the servomotor through Python . . . . . . . . . . . . . . 96
9.4.1 Controlling the servomotor . . . . . . . . . . . . . . . . . . . 96
9.4.2 PythonCode ........................... 97
10 Interfacing a DC Motor 103
10.1Preliminaries ............................... 103
10.2 Controlling the DC motor from Arduino . . . . . . . . . . . . . . . . 105
10.2.1 Controlling the DC motor . . . . . . . . . . . . . . . . . . . . 105
10.2.2 ArduinoCode........................... 108
10.3 Controlling the DC motor from Python . . . . . . . . . . . . . . . . 109
10.3.1 Controlling the DC motor . . . . . . . . . . . . . . . . . . . . 109
10.3.2 PythonCode ........................... 112
vi Contents
11 Implementation of Modbus Protocol 117
11.1Preliminaries ............................... 117
11.1.1 Energymeter ........................... 119
11.1.2 Endianness ............................ 122
11.2 Setup for the experiment . . . . . . . . . . . . . . . . . . . . . . . . . 124
11.3 Software required for this experiment . . . . . . . . . . . . . . . . . . 125
11.3.1 Arduino Firmware . . . . . . . . . . . . . . . . . . . . . . . . 127
11.4 Manifestation of Modbus protocol through Python . . . . . . . . . . 127
11.5 Reading the electrical parameters from Python . . . . . . . . . . . . 129
11.5.1 Reading the electrical parameters . . . . . . . . . . . . . . . . 129
11.5.2 PythonCode ........................... 129
A Procuring the Hardware 131
References 133
List of Figures
2.1 Functional block diagram of a microcontroller . . . . . . . . . . . . . 4
2.2 ADCresolution.............................. 6
2.3 The logo of Open Source Hardware . . . . . . . . . . . . . . . . . . . 7
2.4 ArduinoUnoBoard ........................... 9
2.5 Arduino Mega Board . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.6 LilyPad Arduino Board . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.7 ArduinoPhone .............................. 11
2.8 3Dprinter................................. 12
2.9 PCB image of the shield . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.10 Pictorial representation of the schematic of the shield . . . . . . . . . 14
2.11PCBoftheshield............................. 15
2.12 Picture of the shield with all components . . . . . . . . . . . . . . . . 16
3.1 Windows device manager . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2 Windows device manager . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3 Windows update driver option . . . . . . . . . . . . . . . . . . . . . . 23
3.4 Linux terminal to launch Arduino IDE . . . . . . . . . . . . . . . . . 24
3.5 ArduinoIDE ............................... 24
3.6 Installing Python 3 on Windows . . . . . . . . . . . . . . . . . . . . 29
3.7 Launching the Command Prompt on Windows . . . . . . . . . . . . 29
3.8 Command Prompt on Windows . . . . . . . . . . . . . . . . . . . . . 29
4.1 Light Emitting Diode . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.2 Internal connection diagram for the RGB LED on the shield . . . . . 36
4.3 Connecting Arduino Uno and shield . . . . . . . . . . . . . . . . . . 36
4.4 An RGB LED with Arduino Uno using a breadboard . . . . . . . . . 37
4.5 LED experiments directly on Arduino Uno board, without the shield 40
5.1 Internal connection diagram for the pushbutton on the shield . . . . 50
5.2 A pushbutton to read its status with Arduino Uno using a breadboard 50
vii
viii List of Figures
5.3 A pushbutton to control an LED with Arduino Uno using a breadboard 51
6.1 Light Dependent Resistor . . . . . . . . . . . . . . . . . . . . . . . . 60
6.2 Internal connection diagram for the LDR on the shield . . . . . . . . 60
6.3 An LDR to read its values with Arduino Uno using a breadboard . . 61
6.4 An LDR to control an LED with Arduino Uno using a breadboard . 62
7.1 Potentiometer’s schematic on the shield . . . . . . . . . . . . . . . . 70
7.2 A potentiometer to control an LED with Arduino Uno using a bread-
board ................................... 71
8.1 Pictorial and symbolic representation of a thermistor . . . . . . . . . 78
8.2 Internal connection diagrams for thermistor and buzzer on the shield 78
8.3 A thermistor to read its values with Arduino Uno using a breadboard 79
8.4 A thermistor to control a buzzer with Arduino Uno using a breadboard 80
9.1 Connecting servomotor to the shield attached on Arduino Uno . . . . 90
9.2 A servomotor with Arduino Uno using a breadboard . . . . . . . . . 91
9.3 A servomotor and a potentiometer with Arduino Uno using a bread-
board ................................... 92
10.1 L293D motor driver board . . . . . . . . . . . . . . . . . . . . . . . . 104
10.2 PWM pins on an Arduino Uno board . . . . . . . . . . . . . . . . . . 105
10.3 A schematic of DC motor connections . . . . . . . . . . . . . . . . . 106
10.4 How to connect the DC motor to the Arduino Uno board . . . . . . 106
11.1 Block diagram representation of the Protocol . . . . . . . . . . . . . 118
11.2 Cycle of query-response between master and slave . . . . . . . . . . . 118
11.3 Pins in RS485 module . . . . . . . . . . . . . . . . . . . . . . . . . . 119
11.4 Block diagram for reading the parameters in energy meter . . . . . . 124
11.5 Experimental set up for reading energy meter . . . . . . . . . . . . . 125
11.6 Flowchart of Arduino firmware . . . . . . . . . . . . . . . . . . . . . 126
11.7 Flowchart of the steps happening in the FLOSS code . . . . . . . . . 128
List of Tables
2.1 Arduino Uno hardware specifications . . . . . . . . . . . . . . . . . . 10
2.2 Values of components used in the shield . . . . . . . . . . . . . . . . 15
2.3 Information on sensors and pin numbers . . . . . . . . . . . . . . . . 16
2.4 Lists of components to work with the breadboard . . . . . . . . . . . 17
9.1 Connecting a typical servomotor to Arduino Uno board . . . . . . . 90
10.1 Values to be passed for different H-Bridge circuits . . . . . . . . . . . 104
11.1 Pins available on RS485 and their usage . . . . . . . . . . . . . . . . 119
11.2 Operations supported by Modbus RTU . . . . . . . . . . . . . . . . . 120
11.3 Individual parameter address in EM6400 . . . . . . . . . . . . . . . . 120
11.4 A request packet to access V1 in EM6400 . . . . . . . . . . . . . . . 121
11.5 A response packet to access V1 in EM6400 . . . . . . . . . . . . . . . 122
11.6 Memory storage of a four-byte integer in little-endian and big-endian 123
A.1 Approximate cost of the components . . . . . . . . . . . . . . . . . . 131
ix
xList of Tables
List of Arduino Code
3.1 First 10 lines of the FLOSS firmware . . . . . . . . . . . . . . . . . 27
4.1 Turning on the blue LED . . . . . . . . . . . . . . . . . . . . . . . 40
4.2 Turning on the blue LED and turning it off after two seconds . . . 40
4.3 Turning on blue and red LEDs for 5 seconds and then turning them
offonebyone.............................. 41
4.4 Blinking the green LED . . . . . . . . . . . . . . . . . . . . . . . . 41
5.1 Read the status of the pushbutton and display it on the Serial Monitor 53
5.2 Turning the LED on or off depending on the pushbutton . . . . . . 53
6.1 Read and display the LDR values . . . . . . . . . . . . . . . . . . . 64
6.2 Turning the red LED on and off . . . . . . . . . . . . . . . . . . . . 64
7.1 Turning on LEDs depending on the potentiometer threshold . . . . 72
8.1 Read and display the thermistor values . . . . . . . . . . . . . . . . 82
8.2 Turning the buzzer on using thermistor values . . . . . . . . . . . . 83
9.1 Rotating the servomotor to a specified degree . . . . . . . . . . . . 94
9.2 Rotating the servomotor to a specified degree and reversing . . . . 94
9.3 Rotating the servomotor in increments . . . . . . . . . . . . . . . . 95
9.4 Rotating the servomotor through the potentiometer . . . . . . . . . 95
10.1 Rotating the DC motor . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.2 Rotating the DC motor in both directions . . . . . . . . . . . . . . 108
10.3 Rotating the DC motor in both directions in a loop . . . . . . . . . 109
11.1 First 10 lines of the firmware for Modbus Energy Meter experiment 127
xi
xii List of Arduino Code
List of Python Code
3.1 A Python script to check whether the firmware is properly installed
ornot .................................. 32
4.1 Turning on the blue LED . . . . . . . . . . . . . . . . . . . . . . . 44
4.2 Turning on the blue LED and turning it off after two seconds . . . 44
4.3 Turning on blue and red LEDs for 5 seconds and then turning them
offonebyone.............................. 45
4.4 Blinking the green LED . . . . . . . . . . . . . . . . . . . . . . . . 46
5.1 Read the status of the pushbutton and display it on the Command
Prompt or the Terminal . . . . . . . . . . . . . . . . . . . . . . . . 55
5.2 Turning the LED on or off depending on the pushbutton . . . . . . 56
6.1 Read and display the LDR values . . . . . . . . . . . . . . . . . . . 66
6.2 Turning the red LED on and off . . . . . . . . . . . . . . . . . . . . 66
7.1 Turning on LEDs depending on the potentiometer threshold . . . . 74
8.1 Read and display the thermistor values . . . . . . . . . . . . . . . . 85
8.2 Turning the buzzer on using thermistor values . . . . . . . . . . . . 86
9.1 Rotating the servomotor to a specified degree . . . . . . . . . . . . 97
9.2 Rotating the servomotor to a specified degree and reversing . . . . 98
9.3 Rotating the servomotor in steps of 20◦................ 99
9.4 Rotating the servomotor to a degree specified by the potentiometer 100
10.1 Rotating the DC motor . . . . . . . . . . . . . . . . . . . . . . . . . 112
10.2 Rotating the DC motor in both directions . . . . . . . . . . . . . . 113
10.3 Rotating the DC motor in both directions in a loop . . . . . . . . . 114
11.1 Code for Single Phase Current Output . . . . . . . . . . . . . . . . 129
xiii
List of Acronyms
ACM Abstract Control Model
ADC Analog to Digital Converter
ADK Accessory Development Kit
ALU Arithmetic and Logic Unit
ARM Advanced RISC Machines
BIOS Basic Input/ Output System
CD Compact Disc
CNES National Centre for Space Studies
COM Port Communication Port
CPU Central Processing Unit
DAC Digital to Analog Converter
DC Direct Current
DIY Do It Yourself
DVD Digital Versatile Disc
EEPROM Electronically Erasable Programmable Read-Only Memory
FPGA Field-programmable Gate Array
GNU GNU’s Not Unix
GPS Global Positioning System
GPL General Public License
GSM Global System for Mobile Communications
GUI Graphical User Interface
ICSP In-Circuit Serial Programming
IDE Integrated Development Environment
LAPACK Linear Algebra Package
LCD Liquid Crystal Display
LDR Light Dependent Resistor
LED Light Emitting Diode
xv
xvi List of Acronyms
MRI Magnetic Resonance Imaging
MISO Master Input, Slave output
MOSI Master out, Slave input
NTC Negative Temperature Coefficient
OGP Open Graphics Project
OS Operating System
OSHW Open Source Hardware
PCB Printed Circuit Board
PTC Positive Temperature Coefficient
PWM Pulse width modulation
RAM Random-access Memory
ROM Read Only Memory
RS Recommended Standard
RTC Real Time Clock
Rx Receiver
SD Card Secure Digital Card
SPI Serial Peripheral Interface
SRAM Static Random Access Memory
TCL Tool Command Language
Tx Transmitter
UART Universal Asynchronous Receiver/Transmitter
USB Universal Serial Bus
Chapter 1
Introduction
Microcontrollers are the foundation for a modern, manufacturing-based economy.
One cannot fulfill the dreams of one’s citizens without a thriving manufacturing
sector. As it is open-source, Arduino Uno is of particular interest to hobbyists, stu-
dents, small and medium scale manufacturers, and people from developing countries,
in particular.
Scilab is a state-of-the-art computing software. It is also open-source. As a
result, this is also extremely useful to the groups mentioned above. If the French
National Space Agency CNES can extensively use Scilab [1], why can’t others rely
on it? If many of India’s satellites can be placed in their precise orbits by the Ariane
rockets launched by CNES through Scilab calculations, why can’t others use Scilab?
The above argument can be extended to other open-source software systems
Python, Julia, and OpenModelica. Python is a versatile programming language
with a high degree of expressiveness, which allows code written in it to be small.
Python is also the preferred language in emerging areas, such as machine learning.
Julia is also highly expressive, just as Scilab and Python. The only difference is
that Julia is generally faster to execute, compared to Scilab and Python.
OpenModelica implements the Modelica language. It is especially created for
modeling. It is an object-oriented programming language, especially when it comes
to modeling. It has a GUI that lends itself to connecting different building blocks
to create models. Models in OpenModelica are solved by collecting equations from
different building blocks and solving them simultaneously.
Xcos is a GUI based system building tool for Scilab, somewhat similar to Simulink®1.
Through Xcos, it is possible to build interconnected systems graphically. Xcos also
is an open-source software tool.
Although Scilab, Xcos, Python, Julia, and OpenModelica are powerful and free,
1Simulink®is a registered trademark of Mathworks, Inc.
21. Introduction
there has not been much literature that teaches how to use them to program the
versatile Arduino Uno. To address this gap, we have written this series of books.
We have provided code written in all of these open-source software. The reader is
recommended to go through the book that covers a particular software.
The only way we can become versatile in hardware is through hands-on training.
To this end, we make use of the easily available low-cost Arduino Uno board to
introduce the reader to computer interfacing. We also make available the details
of a shield that makes the Arduino Uno use extremely easy and intuitive. We tell
the user how to install the firmware to make the Arduino Uno board communicate
with the computer. We explain how to control the peripherals on the Arduino Uno
board with user-developed software.
The Scilab-Arduino toolbox is already available for Windows [2]. We have
suitably modified it so that it works on Linux also. We give the required programs
to experiment with the sensors and actuators that come with the shield, a DC motor,
and a servomotor. These programs are available for all of the following environments:
Arduino IDE, Scilab, Xcos, Python, Julia, and OpenModelica. In addition to these
toolboxes, we provide the firmware for each software and a program to check its
working.
This book teaches how to access the following sensors and actuators: LED, push-
button, LDR, Potentiometer, Thermistor, Servo motor, and DC motor. A set of two
to five programs are given for each. These are given for all the software mentioned
above. The reader has to see the book devoted to the appropriate software. We also
explain where to find these programs and how to execute them for each experiment.
This book is written for self-learners and hobbyists. It has been field-tested by
250 people who attended a hands-on workshop conducted at IIT Bombay in July
2015. It has also been field-tested by 25 people who participated in a TEQIP course
held in Amravati in November 2015.
All the code described in this book is available at https://floss-arduino.
fossee.in/downloads. On downloading and unzipping it, it will open a folder
Origin in the current directory. All the files mentioned in this book are with
reference to this folder2.
2This naming convention will be used throughout this book. Users are expected to download
this file and use it while reading this book.
Chapter 2
Hardware Environment
In this book, we shall use an Arduino Uno board and associated circuitry to perform
several experiments on data acquisition and control. This chapter will briefly take
you through the hardware environment needed to perform these experiments. We will
start with the introduction to a microcontroller followed by a brief on Open Source
Hardware. Then, we shall go through the history and hardware specifications of the
Arduino Uno board and the schema and uses of the shield provided in the kit.
2.1 Microcontroller
A microcontroller is a “smart” and complex programmable digital circuit that con-
tains a processor, memory and input/output peripherals on a single integrated cir-
cuit. Effectively, it can function as a small computer that can perform a variety of
applications. A few of these day-to-day applications include:
•Automotive: Braking, driver assist, fault diagnosis, power steering
•Household appliances: CD/DVD players, washing machines, microwave ovens,
energy meters
•Telecommunication: Mobile phones, switches, routers, ethernet controllers
•Medical: Implantable devices, MRI, ultrasound, dental imaging
•General: Automation, safety systems, electronic measurement instruments
2.1.1 Organization of a Microcontroller
In this section, we will give a brief overview of the organization of a typical micro-
controller. A microcontroller consists of three major components, namely, Processor,
42. Hardware Environment
Figure 2.1: Functional block diagram of a microcontroller
Memory and Peripherals. The basic block diagram of a microcontroller is shown in
Fig. 2.1. We shall briefly review the functionality of each block.
Processor: It is also known as a Central Processing Unit (CPU). A processor is the
heart of any computer/embedded system. The applications running on these
systems involve arithmetic and logic operations. These operations are further
simplified into instructions and fed to the processor. The Instruction decoder
decodes these instructions while arithmetic and logic operations are taken care
of by an Arithmetic and Logic Unit (ALU). A modern day CPU can execute
millions of instructions per second (MIPS).
Memory: A computer memory, usually a semiconductor device, is used to hold data
and instructions. Depending on the make, it could be volatile or non-volatile
in nature. There are different types of memory:
1. Read Only Memory (ROM): It is a non-volatile storage entity. It is used
in computers, phones, modems, watches and other electronic devices. A
program is typically uploaded (flashed) to ROM through PC. Its content
2.1. Microcontroller 5
cannot be modified; it can only be erased and flashed using compatible
tools.
2. Random-access Memory: RAM is a volatile storage entity. It is used by
CPU to store intermediate data during the execution of a program. RAM
is usually faster than ROM.
3. Electronically Erasable Programmable Read-Only Memory: EEPROM is
an optional non-volatile storage entity. It can be erased and written by
the running program. For example, it can be used to store the values of
a temperature sensor connected to the microcontroller.
2.1.2 Microcontroller Peripherals
Microcontrollers have a few built-in peripherals. In this section, we will review them
briefly.
Clock: A complex digital circuit, such as the one that is present in a microcontroller,
requires a clock pulse to synchronize different parts of it. The clock is generated
through internal or external crystal oscillator. A typical microcontroller can
execute one instruction per clock cycle (time between two consecutive clock
pulses).
Timer/Counter: A timer is a pulse counter. A timer circuit is controlled by reg-
isters. An 8-bit timer can count from 0 to 255. A timer is primarily used to
generate delay, and could be configured to count events.
Input/Output Ports: I/O ports correspond to physical pins on the microcontroller.
They are used to interface external peripherals. A port can be configured as
input or output by setting bits in I/O registers. Each pin can be individually
addressed too.
Interrupts: An interrupt to the CPU suspends the running program and executes
a code block corresponding to it. After serving/attending interrupts, the CPU
resumes the previous program and continues. An interrupt could be originated
by the software or the hardware. A hardware interrupt normally has a higher
priority.
Universal Asynchronous Receiver/Transmitter (UART): UART is a standard mi-
crocontroller peripheral to communicate with external serial enabled devices.
It has two dedicated pins to be used as Rx (Receiver) and Tx (Transmitter).
The baud rate defines the speed of the UART and can be configured using
registers.
62. Hardware Environment
Figure 2.2: ADC resolution
Analog to Digital Converter (ADC): Most of the signals around us are continuous.
Digital circuits cannot process them. An ADC converts them into digital
signals. The resolution of the ADC determines the efficiency of conversion. For
example, a 10-bit resolution of the ADC relates to 1024 values per sample. This
is shown pictorially in Fig. 2.2. Higher resolution relates to better translation
of an analog signal.
Digital to Analog Converter (DAC): Digital output of the CPU is converted to ana-
log signals using the pulse width modulation (PWM) technique. The output
of a DAC is used to drive analog devices and actuators.
Serial Peripheral Interface (SPI): SPI is a synchronous 4 wire serial communication
device. It requires a master and slave configuration. The SPI peripheral has
dedicated pins and marked as:
1. SCLK (from Master)
2. MOSI (Master out, Slave input)
3. MISO (Master Input, Slave output)
4. Slave select (Active when 0V, originates from Master)
Firmware: Firmware is an application that configures the hardware. It is pro-
grammed to a non-volatile memory such as ROM, EPROM (Erasable Pro-
grammable ROM). This concept is used in computer BIOS and embedded
2.2. Open Source Hardware (OSHW) 7
Figure 2.3: The logo of Open Source Hardware
devices. In a microcontroller setup, a firmware file contains addresses and
hexadecimal values.
Interfacing: Some of the popular connections with microcontrollers include,
1. Digital input devices: Switch, keypad, encoder, multiplexer, touchscreen
2. Digital output devices: LED, LCD, relay, buzzer
3. Digital input and output devices: RTC (Real Time Clock), SD Card,
external ROM
4. Analog input devices: Audio, sensor, potentiometer
5. Analog output devices: Brightness control, speaker
6. Serial communication (UART): GSM, GPS, Zigbee, Bluetooth
2.2 Open Source Hardware (OSHW)
In this section, we will introduce the reader to Open Source Hardware (OSHW),
which is defined as follows [3]:
Open source hardware is a hardware whose design is made publicly avail-
able so that anyone can study, modify, distribute, make, and sell the
design or hardware based on that design...
The OSHW website [3] gives additional conditions to be fulfilled before the hardware
can be called OSHW. It also argues why we should promote and contribute to OSHW.
The logo of OSHW is given in Fig. 2.3 [4]. The open-source hardware initiative is
popular in the electronic, computing hardware and automation industry. Here are
some examples of open-source hardware projects:
1. The “open compute project” at Facebook shares the design of data center
products.
2. Beagle board, Panda board, OLinuXino are ARM based development boards.
82. Hardware Environment
3. “Open Graphics Project (OGP)” releases the designs of graphics card.
4. “ArduCopter” is a UAV (unmanned aerial vehicle) created by the DIY Drones
community.
5. “NetFPGA” is a prototyping of computer network devices.
6. “OpenROV” project (Open Source Remotely Operated Vehicle) aims at afford-
able underwater exploration.
7. “OpenMoko” project set the foundation for open-source mobile phones. “Neo
1973” was the first smartphone released in 2007 with Linux based operating
system, it had 128MB RAM and 64MB ROM.
Companies like Adafruit Industries, Texas Instruments, Solarbotics, Sparkfun
electronics, MakerBot industries and DIY Drones have proven the power of OSHW
with their revenues. Nevertheless, collaborative innovation using OSHW is yet to
establish itself in the mainstream. But the trend has certainly started and is going
strong. There are now many robotics startups taking full use of OSHW.
2.3 Arduino
Arduino is an open-source microcontroller board and a software development en-
vironment. Arduino language is a Clike programming language which is easy to
learn and understand. Arduino has two components, open source hardware and open
source software. We will cover the basics of the Arduino hardware in this section.
2.3.1 Brief History
Arduino project was started at the Interaction Design Institute Ivrea in Ivrea, Italy.
The aim was to create a low-cost microcontroller board that anyone with little or
no background domain knowledge can design and develop. Arduino uses expansion
circuit boards known as shields. Shields can provide GPS, GSM, Bluetooth, Zigbee,
motor and other functionality.
Within the first two years of its inception, the Arduino Team sold more than
50,000 boards. In 2011, Google announced The Android Open Accessory Develop-
ment Kit (ADK), which enables the Arduino boards to interface with Android mobile
platform.
Today Arduino is the first choice for electronic designers and hobbyists. There
are more than 13 official variants of Arduino and many more third-party Arduino
software compatible boards.
2.3. Arduino 9
Figure 2.4: Arduino Uno Board
2.3.2 Arduino Uno Board
There are different Arduino boards for different requirements. All original Arduino
boards are based on ATMEL microcontrollers. In this section, we will briefly discuss
the Arduino Uno board, the most popular Arduino board. We will illustrate all
applications using the Arduino Uno board in this book.
Based on ATmega328, the Arduino Uno board has 14 digital input/output pins,
6 analog inputs, 6 PWM pins, a 16 MHz ceramic resonator, a power jack, an ICSP
(In-Circuit Serial Programming) header, and a reset button. It has an on-board
USB to serial converter and can be connected to a PC using a USB cable. Fig. 2.4
has a picture of this board [5]. Table 2.1 has the specifications of the Arduino Uno
board.
Another popular board is Arduino Mega board. Based on ATmega2560, this
board has almost double the size of program memory (ROM) compared to Arduino
Uno. It also has extra serial ports, digital and PWM pins. Fig. 2.5 has a picture of
this board [6].
Yet another popular board is LilyPad Arduino, a small circular board for fabric
designers. It can be stitched with conductive thread, and it supports sensors and
actuators. Fig. 2.6 has a picture of this board [7].
There are other similar configuration boards with different form factors, such as
Arduino Fio, Arduino Mini, Arduino Nano, Arduino Duemilanove, Arduino serial
and so on.
2.3.3 Popular Arduino Projects
Arduino is intuitive and it’s easy to setup and use. That’s why people around the
globe are using Arduino in innovative ways. We list a few of these projects to give
10 2. Hardware Environment
Parameter Value
Microcontroller ATmega328P
Operating Voltage 5V
Input Voltage (recommended) 7-12V
Input Voltage (limits) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
Analog Input Pins 6
DC Current per I/O Pin 20 mA
DC Current for 3.3V Pin 50 mA
Flash Memory 32 KB (ATmega328), 0.5 KB used by bootloader
SRAM 2 KB (ATmega328)
EEPROM 1 KB (ATmega328)
Clock Speed 16 MHz
Length 68.6 mm
Width 53.4 mm
Weight 25 g
Table 2.1: Arduino Uno hardware specifications
Figure 2.5: Arduino Mega Board
a flavor of some of these interesting applications.
Arduino phone: An Arduino connected with a graphic LCD and a GSM shield.
This low-tech phone, shown in Fig. 2.7 can be built in a few hours [8].
2.4. Shield 11
Figure 2.6: LilyPad Arduino Board
Figure 2.7: Arduino Phone
Candy sorting machine: As the name suggests, this machine can sort candy
based on its color to separate jars [9].
3D printers: There are open-source 3D printers based on Arduino and Raspberry
Pi. Although 3D printers, shown in Fig. 2.8, are relatively slow and lack precision,
they can be ideal for building prototypes by hobbyists [10].
2.4 Shield
The shield that we use in this book is a modified version of the Diyode Codeshield
board [11], which makes it easy to perform experiments on the Arduino Uno board.
12 2. Hardware Environment
Figure 2.8: 3D printer
The shield is a printed circuit board (PCB) with a large number of sensors, already
wired and hence, ready to use. It obviates the need for a breadboard as an intermedi-
ate tool for electronics circuit prototyping, which is quite cumbersome for beginners.
The shield provides the user a faster way of circuit prototyping without worrying
much about troubleshooting.
The numbering on the shield is identical to that on the Arduino Uno board.
The shield fits snugly on to the Arduino Uno board, obviating the need to do the
wiring in many experiments. One can even say that shields have made the hardware
experiments involving Arduino boards as easy as writing software.
All the experiments in this book have been verified with the use of a modified ver-
sion of Diyode Codeshield, as mentioned above. We make available all the required
information to make a shield, thus making this an OSHW, see Sec. 2.2.
We now explain where the required files to make our shield are given. The
gerber file to make the shield is given in Origin/tools/shield/gerber-V1.2,
see Footnote 2 on page 2. The image of the PCB file is given in Fig. 2.9. The PCB
project files are available in a folder at Origin/tools/shield/kicad-import,
see Footnote 2 on page 2. The pictorial representation of the schematic for the shield
is given in Fig. 2.10. A photograph of the PCB after fabrication is given in Fig. 2.11.
The values of the various components used in the shield are given in Table 2.2.
Table 2.3 provides information about various sensors, components on shield and its
corresponding pin on Arduino Uno board [11]. A picture of the completed shield is
in Fig. 2.12. The information on purchasing this shield is given in Appendix A.
2.5 Experimental Test Bed
We experimented with the contents of this book with the following list. We will refer
to this as a kit in the rest of this book.
1. Arduino Uno board
2. Shield containing
2.6. Doing the Experiments with a Breadboard 13
Figure 2.9: PCB image of the shield
(a) LED
(b) LDR
(c) Push Button
(d) Thermistor
3. DC motor and its controller board
4. Servomotor
5. Energy meter with Modbus interface
The Arduino Uno board is easily available in the market. The shield is designed
by us. Details of most of these units are provided in the previous sections. Infor-
mation on all of these is available in the file, mentioned in Footnote 2, and in the
Appendix.
2.6 Doing the Experiments with a Breadboard
It is possible to carry out many of the experiments listed in this book using a bread-
board. For example, carrying out experiments with an LED is explained in Sec. 4.2.
2.6. Doing the Experiments with a Breadboard 15
Figure 2.11: PCB of the shield
Table 2.2: Values of components used in the shield
Name Description Quantity
R1, R10 100Ω Resistor (Br-Bl-Br) 2
R2, R3 91Ω Resistor (Wt-Br-Bl) 2
R6, R7, R8 10KΩResistor (Br-Bl-Or) 3
R9 1KΩResistor (Br-Bl-Rd) 1
D1 Diode 1
Relay Relay 1
X1 Terminal block 1
Piezo Buzzer 1
RGB RGB LED 1
T1 Transistor 1
BUTTON Pushbutton 1
PHOTO Light dependent resistor 1
HALL Hall effect sensor 1
POT Potentiometer 1
THERM Thermistor 1
SERVO Servomotor 1
HEADER 6x pin header 2
HEADER 8x pin header 2
16 2. Hardware Environment
Table 2.3: Information on sensors and pin numbers
Shield components Arduino pin
RELAY Digital pin 2
BUZZER Digital pin 3
SERVO Digital pin 5
RGB LED BLUE Digital pin 9
RGB LED GREEN Digital pin 10
RGB LED RED Digital pin 11
PUSHBUTTON Digital pin 12
POTENTIOMETER Analog pin 2
HALL EFFECT SENSOR Analog pin 3
THERMISTOR Analog pin 4
PHOTORESISTOR (LDR) Analog pin 5
Figure 2.12: Picture of the shield with all components
2.6. Doing the Experiments with a Breadboard 17
Table 2.4: Lists of components to work with the breadboard
Components Quantity
Arduino Uno with USB cable 1
Half breadboard 1
Male to Male jumper wires 10
100Ω Resistor 5
10KΩResistor 2
RGB LED 1
Pushbutton 1
Photoresistor (LDR) 1
Potentiometer 1
Thermistor 1
Buzzer 1
Servomotor 1
L293D motor driver board 1
DC motor 1
18 2. Hardware Environment
Chapter 3
Communication between Software
and Arduino
In this chapter, we shall briefly walk through the software environment that needs to
be set up before we could start with the Arduino Uno board-based experiments. We
shall start with the Arduino Uno compatible Integrated Development Environment
(IDE), termed as Arduino IDE, that would be used to load the FLOSS firmware on
to the microcontroller. The FLOSS firmware to be loaded could be developed to
serve different purposes as per the requirement. For example,
•To run Arduino Uno stand-alone, without waiting for any commands from
other software or hardware, for the specified time or until power off
•To decode the commands sent by other software, such as Scilab, Python, Julia,
OpenModelica, etc., through a serial port, and execute the given instructions
Next, we shall discuss other open-source software tools and a related toolbox that
can communicate with Arduino Uno over a serial port using RS232 protocol.
3.1 Arduino IDE
Arduino development environment is compatible with popular desktop operating
systems. In this section, we will learn to set up this tool for the computers running
Microsoft Windows or Linux. Later, we shall explore the important menu options
in the Arduino IDE and run a sample program. The following two steps have to be
followed whatever operating system is used:
1. To begin, we need an Arduino Uno board with a USB cable (A plug to B plug)
as shown in Fig. 2.4.
20 3. Communication between Software and Arduino
2. Connect it to a computer and power it up. The moment you connect Arduino
Uno to the computer, an on-board power LED will turn ON.
3.1.1 Downloading and installing on Windows
First, carry out the steps numbered 1 and 2 given above. Starting from download,
we shall go through the steps to set up Arduino IDE on Windows OS:
3. Visit the URL, https://www.arduino.cc/en/software. On the right
right side of the page, locate the link Windows ZIP file and click on it. This
may redirect you to the download/donate page. Read the instructions and
proceed with the download.
4. Extract the downloaded ZIP file to Desktop. Do not alter any file or directory
structure.
5. Click on the Windows Start Menu, and open up the “Control Panel”.
6. While in the Control Panel, navigate to “System and Security”, click on “Sys-
tem” and then choose the “Device Manager”.
7. Look for “Other devices” in the “Device Manager” list, expand and locate “Un-
known device”. This may be similar to what is shown in Fig. 3.1. In case, you
don’t see “Unknown device,” look for “Ports (COM & LPT)” and expand it to
locate “USB Serial Device (COM2)”. This may be similar to what is shown in
Fig. 3.2.
8. Right-click on the “Unknown device” (or “USB Serial Device (COM2)” as shown
in the previous step) and select the “Update Driver Software” (or “Update
driver”) option as shown in Fig. 3.3.
9. Next, choose the “Browse my computer for Driver software” option.
10. Navigate to the newly extracted Arduino folder on the Desktop and select
“drivers” folder.
11. Windows will now finish the driver installation. The Arduino IDE is ready for
use.
To launch Arduino IDE, browse to extracted Arduino folder on the Desktop and
double click on “arduino.exe”.
3.1. Arduino IDE 21
Figure 3.1: Windows device manager
3.1.2 Downloading and installing on GNU/Linux Ubuntu
We will now explain the installation of Arduino software on the GNU/Linux oper-
ating system. We shall perform the installation on the 64-bit Ubuntu 18.04 LTS
operating system. These instructions will work for other GNU distributions too,
with little or no modification. First, carry out the steps numbered 1 and 2 given
above. Then carry out the following:
3. First, update your system. Open the terminal emulator, type, sudo apt-get
update and press Enter.
4. Find out your operating system support for 64-bit instructions. Open the
terminal emulator and type, uname -m
5. If it returns “x86_64”, then your computer has 64-bit operating system. There
is no visible performance difference in 32 and 64-bit Arduino versions.
22 3. Communication between Software and Arduino
Figure 3.2: Windows device manager
6. Download the suitable Arduino Software version (32 or 64-bit) from
https://www.arduino.cc/en/software. As mentioned earlier, we will
perform experiments with a 64-bit installation.
7. At the time of writing this book, we worked with version 1.8.13. Assuming
that you have downloaded the tar file in the Downloads directory, execute the
following commands on the terminal:
cd ~/Downloads
tar -xvf arduino-1.8.13-linux64.tar.xz
sudo mv arduino-1.8.13 /opt
8. In the same terminal session, install the required Java Runtime Environment
with a command like, sudo apt-get -y install openjdk-8-jre
9. Execute the following command on the terminal to list the serial port number.
ls /dev/ttyACM*
3.1. Arduino IDE 23
Figure 3.3: Windows update driver option
Note down the serial device filename. Suppose that it is ttyACM0.
10. To make the USB port available to all users, set the read-write permission to
the listed port: sudo chmod a+rw /dev/ttyACM0. Each time you plug
the Arduino Uno into the computer, you need to execute the commands given
in the steps numbered 9 and 10.
The Arduino IDE is now ready for use. To launch it, carry out the steps given below:
1. Open a terminal by pressing the Alt+Ctrl+T keys together.
2. Navigate into the opt directory, as shown in Fig. 3.4.
cd /opt/arduino-1.8.13/
3. Start the Arduino IDE by executing the command ./arduino
3.1.3 Arduino Development Environment
The Arduino development environment, as shown in Fig. 3.5, consists of a text editor
for writing code, a message area, a text console, a toolbar with buttons for common
24 3. Communication between Software and Arduino
Figure 3.4: Linux terminal to launch Arduino IDE
Figure 3.5: Arduino IDE
functions, and a series of menus. It connects to the Arduino hardware to upload
programs and communicate with them.
Software written using Arduino is called sketches. These sketches are written in
3.1. Arduino IDE 25
the text editor. Sketches are saved with the file extension “.ino”. The frequently used
icons shown in the toolbar, below the menu bar, are explained next. The names of
these icons can be viewed by hovering the mouse pointer over each of them.
1. Verify: Checks your code for errors
2. Upload: Compiles your code and uploads it to the Arduino I/O board
3. New: Creates a new sketch
4. Open: Presents a menu of all the sketches in your sketchbook - clicking one
will open it within the current window
5. Save: Saves your sketch
6. Serial Monitor: Opens the serial port window - the location of this is shown in
the top right-hand corner of Fig. 3.5
Note that these appear from left to right in the editor window. Next, we shall go
through the additional useful options under the menu.
1. File
(a) Examples: Examples that come at the time of installation
(b) Page Setup: Configures the page parameters for the printer
(c) Preferences: Customizes font, language, and other parameters for the IDE
2. Sketch
(a) Include Library: Adds a library to your sketch by inserting #include
statements at the start of your code
3. Tools
(a) Auto Format: Indents code so that opening and closing curly braces line
up
(b) Archive Sketch: Archives a copy of the current sketch in .zip format. The
archive is placed in the same directory as the sketch.
(c) Board: Selects the board that you’re using
(d) Port: This menu contains all the serial devices (real or virtual) on your
machine. It should automatically refresh every time you open the top-
level tools menu.
26 3. Communication between Software and Arduino
(e) Programmer: This can be used to select a hardware programmer when
programming a board or chip and not using the onboard USB-serial con-
nection. Normally you won’t need this, but if you’re burning a bootloader
to a new microcontroller, you will use this.
(f) Burn Bootloader: The items in this menu allow you to burn a bootloader
onto the microcontroller on an Arduino board. This is not required for
normal use of an Arduino board but is useful if you purchase a new AT-
mega microcontroller (which normally comes without a bootloader). En-
sure that you’ve selected the correct board from the Boards menu before
burning the bootloader.
3.1.4 Testing Arduino with a sample program
Now, as we have a basic understanding of Arduino IDE, let us try an example
program.
1. Open the Arduino IDE by clicking the shortcut “arduino” from Desktop in
Ubuntu. In MS Windows browse to extracted Arduino folder on Desktop and
double click on “arduino.exe”.
2. In the Arduino IDE, to know the path of your sketch files, navigate to File,
then Preferences and then locate the “Sketchbook location” text box at the
top. You may change the path of your storage location. In this book, we will
keep it unchanged. The path will be different for Windows and Ubuntu.
3. To load a sample program, navigate and click on sketch “File”, then Examples,
then 01.Basics, and then Blink.
4. A new IDE instance will open with Blink LED code. You may close the
previous IDE window now.
5. Click “verify” to compile. The “status bar” below the text editor shall show
“Done compiling” on success.
6. Connect Arduino UNO board to PC. You may connect the board before writing
the sketch too.
7. Now, navigate to “Tools”, then Port, and select the available port. If the port
option is greyed out (or disabled) then reinsert the USB cable to the PC.
8. Now select the upload button to compile and send the firmware to the Arduino
Uno board.
3.2. Python 27
9. If the upload is successful, you will notice the onboard orange LED next to the
Arduino logo will start blinking.
10. It is safe to detach the USB cable at any moment.
Arduino programming syntax is different from other languages. In an embedded
setup, a program is expected to run forever. To facilitate this, the Arduino program-
ming structure has two main functions: setup(): Used to initialize variables, pin
modes, libraries, etc. The setup function will run only once after each powerup or
board reset. loop(): Code inside this function runs forever. An Arduino program
must have setup() and loop() functions. We will give several examples in this
book to explain this usage.
An inbuilt offline help is available within the IDE. You may access the explanation
on IDE by navigating to “Help” and then Environment.
3.1.5 FLOSS Firmware
We have provided a code to check whether the FLOSS firmware has been properly
installed. The first few lines of this code follow.
Arduino Code 3.1 First 10 lines of the FLOSS firmware. Available at Origin
/tools/floss-firmware/floss-firmware.ino, see Footnote 2 on page 2.
Following the steps given in sections 3.1.3 and 3.1.4, open this code in Arduino IDE
and upload it to Arduino Uno. Once the upload is successful, you should expect a
success message at the bottom of Arduino IDE, as shown in Fig. 3.5.
1/∗T h i s f i l e i s m e an t t o b e u s e d w i t h t h e FLOSS−Arduino
2t o o l b o x , h ow e v e r , i t c a n b e u s e d f ro m t h e ID E e n v i r o n m e n t
3( o r any ot he r s e r i a l t e r mi na l ) b y t y p i ng c ommand s l i k e :
4
5C o n v e r s i o n a s c i i −> numb e r
648 −> ’ 0 ’ . . . 5 7 −> ’9 ’ 5 8 −> ’ : ’ 59 −> ’ ; ’ 60−>’< ’ 61−> ’=’ 62 −> ’ >’ 6 3 −> ’? ’
64 −> ’@ ’
765 −> ’A ’ . . . 90−> ’Z ’ 91 −> ’ [ ’ 92 −> ’ \ ’ 93 −> ’] ’ 94 −> ’^ ’ 95 −> ’_ ’ 96 −>’‘’
897 −> ’ a ’ . . . 122 −> ’ z ’
9
10 Dan0 or Dan 1 : a tt ac h d i g i t a l pi n n ( a s c i i f ro m 2 t o b ) t o i n pu t ( 0 )
o r o u t p u t ( 1 )
3.2 Python
Python is a general-purpose, high-level, remarkably powerful dynamic programming
language that is used in a wide variety of application domains. Its high-level built-
in data structures, combined with dynamic typing and dynamic binding, make it
28 3. Communication between Software and Arduino
very attractive for Rapid Application Development, as well as for use as a scripting
or glue language to connect existing components together. Python’s simple, easy
to learn syntax emphasizes readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages program
modularity and code reuse. The Python interpreter and the extensive standard
library are available in source or binary form without charge for all major platforms,
and can be freely distributed [12].
3.2.1 Downloading and installing on Windows
This book uses Python 3 for demonstrating the experiments, both on Windows and
Linux. Since Python uses indentation to indicate a block of code, the users are
advised to install a programmer text editor like Atom. This editor will allow the
readers to modify the Python scripts on their machines if they want to. Starting
from download, we shall go through the steps to set up Python 3 on Windows OS:
1. Visit the URL https://www.python.org/. At the top of the page, locate
the Downloads tab and click on it. At the time of writing this book (as of
21 April 2021), Python 3.9.4 is the latest version. Click on Download Python
3.9.4 to download the executable file. The readers may want to download the
other versions of Python 3. However, we recommend the installation of Python
3.5 or above. It may be noted that some of the Python 3 versions cannot be
used on Windows 7 or earlier.
2. Locate the executable file and double-click on it to begin the installation.
Python 3.9.4 Setup window appears, as shown in Fig. 3.6. In this window,
check the box which says, Add Python 3.9 to PATH and click on Install now.
Once the installation is finished, Python 3.9 App can be launched from the Start
menu. In this book, we will use the Command Prompt to execute the Python scripts.
Please note that a Python script has .py as its extension. Carry out the steps given
below to execute a Python script from the Command Prompt:
1. Launch the Command Prompt. Press the Windows key+R together. A win-
dow, as shown in Fig. 3.7 appears. In the text box adjacent to Open, type
cmd, and press Enter. The Command Prompt, as shown in Fig. 3.8 appears.
By default, it points to the home directory.
2. Now, we will check whether Python 3.9 was installed successfully or not. In
the Command Prompt, type py --version and press Enter. If this step
displays Python 3.9.4 in the following line, the installation was successful.
3.2. Python 29
Figure 3.6: Installing Python 3 on Windows
Figure 3.7: Launching the Command Prompt on Windows
3. Using the cd command, navigate to the directory where your Python script is
located. Assuming that your Command Prompt points to the home directory,
and you want to navigate to the folder Origin on Desktop, execute the following
Figure 3.8: Command Prompt on Windows
30 3. Communication between Software and Arduino
command: cd Desktop\Origin
It may be noted that a backslash (\) has been used between Desktop and
Origin.
4. To view the contents of this folder, type dir and press Enter.
5. Suppose you have a Python script named FILENAME.py in this folder. To ex-
ecute this script, type python FILENAME.py and press Enter. The required
output will be displayed in the Command Prompt itself. We don’t expect the
readers to run the command python FILENAME.py at this instant. This
command will be helpful while running the Python scripts in the upcoming
sections and chapters.
6. To exit the Command Prompt, type exit and press Enter.
Apart from Python, we need to install Python Serial Port Extension, also known
as pyserial [13]. To do so, carry out the steps given below:
1. Launch the Command Prompt, as shown in Fig. 3.7.
2. First, we need to make sure we have pip available. In the Command Prompt,
execute the following command: py -m pip --version
This step should display an output with the version of pip installed.
3. Now, install pyserial. In the Command Prompt, execute the following com-
mand: py -m pip install pyserial
4. We will verify whether the pyserial package was installed successfully or not. In
the Command Prompt, execute the following command: pip show pyserial
It should show the name, version, etc., of the package.
5. To exit the Command Prompt, type exit and press Enter.
3.2.2 Downloading and installing on GNU/Linux Ubuntu
On Linux, we can install Python from the terminal. Please ensure that you are
connected to the Internet. To install Python 3.5, carry out the steps given below:
1. Open a terminal by pressing the Alt+Ctrl+T keys together.
2. Update the system by executing the command sudo apt-get update
3. Install Python3.5 by executing the command given below:
sudo apt-get install python3.5
3.2. Python 31
4. Now, we will check whether Python was installed successfully or not. In the
terminal, type py --version and press Enter. If this step displays Python
3.8.4 in the following line, the installation was successful.
Once the installation is finished, Python 3 can be launched from the terminal.
In this book, we will use the Linux terminal to execute the Python scripts. Please
note that a Python script has .py as its extension. Carry out the steps given below
to execute a Python script from the terminal:
1. Open a terminal by pressing the Alt+Ctrl+T keys together.
2. Using cd command, navigate to the directory where the Python script is lo-
cated.
3. Suppose you have a Python script named FILENAME.py. To execute this
script, type python3 FILENAME.py and press Enter. The required output
will be displayed in the terminal itself. We don’t expect the readers to run
the command python3 FILENAME.py at this instant. This command will
be helpful while running the Python scripts in the upcoming sections and
chapters.
Apart from Python, we need to install Python Serial Port Extension, also known
as pyserial [13]. To do so, carry out the steps given below:
1. Open a terminal by pressing the Alt+Ctrl+T keys together.
2. First, we need to install pip. In the terminal, execute the following command:
sudo apt-get install python3-pip
3. Now, install pyserial. In the terminal, execute the following command:
pip3 install pyserial
4. We will verify whether the pyserial package was installed successfully or not.
In the terminal, execute the following command: pip3 show pyserial
It should show the name, version, etc., of the package.
3.2.3 Python-Arduino toolbox
Python, by default, does not have the capability to connect to Arduino. All such add-
on functionalities are added to Python using packages. The Python-Arduino tool-
box can be found inside the Origin/tools/python directory, see Footnote 2 on
page 2. This toolbox is compatible for both of the operating systems: Windows and
32 3. Communication between Software and Arduino
Linux. The Python scripts (or codes) for various experiments mentioned through-
out this book can be found in Origin/user-code directory. The user-code
directory will have many sub-directories as per the experiments.
In this book, we have created a package named "Arduino" in Python 3. This
package is available at Origin/tools/python. This package makes use of the
functions available in pyserial [13] to establish serial communication with Arduino.
In this package, we have added functions required to run various experiments on
Arduino Uno. Using this basic set of functions, the user can define other functions
to operate upon the Arduino. Please note that the "Arduino" package and the
FLOSS firmware given in Arduino Code 3.1 are required to run the experiments.
Now, we will see how to import (or load) the "Arduino" package inside a Python
script to run various experiments provided in this book. In a Python script, add
from Arduino.Arduino import Arduino at the top of the script. When we
add from Arduino.Arduino import Arduino in a script, the function "from"
searches for "Arduino" only in that directory where our script is saved. That’s why all
the scripts in Python must be saved in a folder that contains the "Arduino" package.
In this book, "Arduino" package has been saved in the folder where the Python
scripts for each chapter are available. For the sake of convenience, we have added
from Arduino.Arduino import Arduino in all the Python scripts provided
in this book. To run a particular experiment, one can follow the steps as given in
Sec. 3.2.1 or Sec. 3.2.2.
3.2.4 Firmware
We have provided a Python code to check whether the firmware has been properly
installed. That code is listed below. Please ensure that you have uploaded the
FLOSS firmware given in Arduino Code 3.1 on the Arduino Uno board.
Python Code 3.1 A Python script to check whether the firmware is properly in-
stalled or not. Available at Origin/tools/python/test_firmware.py, see
Footnote 2 on page 2. Execute this script by following the steps given in Sec. 3.2.1
or Sec. 3.2.2. If the execution is successful, you should expect three "ok" messages.
1import os
2import sys
3cwd = o s . g et c wd ( )
4( s et pa th , E xam ples ) = os . p at h . s p l i t ( cwd )
5sy s . path . a ppe nd ( se tp at h )
6
7from Arduino . Arduino import Arduino
8fr om ti me im p or t s l e e p
9
10 c l a s s TEST_FIRMWARE:
3.2. Python 33
11 d e f __ini t__ ( s e l f , b a u dr a t e ) :
12 s e l f . b au dr at e = bau dr at e
13 s e l f . s et up ( )
14 s e l f . r un ( )
15 s e l f . e xi t ( )
16
17 d ef se tu p ( s e l f ) :
18 s e l f . o bj _a rd ui no = Ardui no ( )
19 s e l f . p o rt = s e l f . o bj _ ar d ui n o . l o c a t e p o r t ( )
20 s e l f . o b j_ a r du i n o . o p e n _ s e r i a l ( 1 , s e l f . p or t , s e l f . b au d r a te )
21
22 d ef run ( s e l f ) :
23 s e l f . o bj _a rd ui no . ch ec kf ir mwa re ( )
24
25 d e f e x i t ( s e l f ) :
26 s e l f . o b j_ ar d ui no . c l o s e _ s e r i a l ( )
27
28 d e f ma in ( ) :
29 obj_ l e d = TEST_FIRMWARE(11 5 20 0 )
30
31 i f __name__== ’__main__ ’ :
32 ma in ( )
34 3. Communication between Software and Arduino
Chapter 4
Interfacing a Light Emitting Diode
In this chapter, we will learn how to control the LEDs on the shield and on the
Arduino Uno board. We will do this through the Arduino IDE and other open-
source software tools. These are beginner level experiments, and often referred to
as the hello world task of Arduino. Although simple, controlling LED is a very
important task in all kinds of electronic boards.
4.1 Preliminaries
A light emitting diode (LED) is a special type of semiconductor diode, which emits
light when voltage is applied across its terminals. A typical LED has 2 leads: Anode,
the positive terminal and Cathode, the negative terminal. When sufficient voltage
is applied, electrons combine with the holes, thereby releasing energy in the form of
photons. These photons emit light and this phenomenon is known as electrolumi-
nescence. The symbolic representation of an LED is shown in Fig. 4.1. Generally,
LEDs are capable of emitting different colours. Changing the composition of alloys
that are present in LED helps produce different colours. A popular LED is an RGB
LED that actually has three LEDs: red, green and blue.
An RGB LED is present on the shield provided in the kit. In this section, we
will see how to light each of the LEDs present in the RGB LED. As a matter of fact,
Figure 4.1: Light Emitting Diode
36 4. Interfacing a Light Emitting Diode
Figure 4.2: Internal connection diagram for the RGB LED on the shield
Figure 4.3: Connecting Arduino Uno and shield
it is possible to create many colours by combining these three. A schematic of the
RGB LED in the shield is given in Fig. 4.2. The anode pins of red, green, and blue
are connected to pins 11, 10, and 9, respectively. Common Cathode is connected to
the ground.
It should be pointed out, however, that no wire connections are to be made by
the learner: all the required connections are already made internally and it is ready
to use. The LED of any colour can be turned on by putting a high voltage on the
corresponding anode pin.
One should remember to connect the shield on to the Arduino Uno board, as
4.2. Connecting an RGB LED with Arduino Uno using a breadboard 37
Figure 4.4: An RGB LED with Arduino Uno using a breadboard
shown in Fig. 4.3. All the experiments in this chapter assume that the shield is
connected to the Arduino Uno board. It is also possible to do some of the experiments
without the shield, which is pointed out in the next section.
4.2 Connecting an RGB LED with Arduino Uno using a
breadboard
This section is useful for those who either don’t have a shield or don’t want to use
the shield for performing the experiments given in this chapter.
A breadboard is a device for holding the components of a circuit and connect-
ing them together. We can build an electronic circuit on a breadboard without
doing any soldering. To know more about the breadboard and other electronic
components, one should watch the Spoken Tutorials on Arduino as published on
https://spoken-tutorial.org/. Ideally, one should go through all the tuto-
rials labeled as Basic. However, we strongly recommend the readers should watch
the fifth and sixth tutorials, i.e., First Arduino Program and Arduino with
Tricolor LED and Push button.
In case you have an RGB LED and want to connect it with Arduino Uno on a
breadboard, please refer to Fig. 4.4. As shown in Fig. 4.4, there is an RGB LED with
four legs. From the left, the first leg represents the anode (+) pin for the red LED.
The second leg represents the common cathode for every color. The third and fourth
legs represent the anode (+) pins for the green LED and blue LED respectively. The
38 4. Interfacing a Light Emitting Diode
anode pins of red, green, and blue are connected to digital pins 11, 10, and 9 of
Arduino Uno, respectively. Common cathode is connected to the ground (GND)
terminal of Arduino Uno.
4.3 Lighting the LED from the Arduino IDE
4.3.1 Lighting the LED
In this section, we will describe some experiments that will help the LED light up
based on the command given from the Arduino IDE. We will also give the necessary
code. We will present four experiments in this section. The shield has to be attached
to the Arduino Uno board before doing these experiments and the Arduino Uno needs
to be connected to the computer with a USB cable, as shown in Fig. 2.4. The reader
should go through the instructions given in Sec. 3.1 before getting started.
1. First, we will see how to light up the LED in different colours. An extremely
simple code is given in Arduino Code 4.1. On uploading this code, you can
see that the LED on the shield turns blue. It is extremely easy to explain this
code. Recall from the above discussion that we have to put a high voltage (5V)
on pin 9 to turn the blue light on. This is achieved by the following command:
1d i g i t a l W r i t e ( 9 , HIGH) ;
Before that, we need to define pin 9 as the output pin. This is achieved by the
command,
1pi nMo de ( 9 , OUTPUT) ;
One can see that the blue light will be on continuously.
2. Next, we will modify the code slightly so that the blue light remains on for
two seconds and then turns off. Arduino Code 4.2 helps achieve this. In this,
we introduce a new command delay as below:
1de l ay ( 20 00 ) ;
This delay command halts the code for the time passed as in input argument.
In our case, it is 2,000 milliseconds, or 2 seconds. The next command,
1d i g i t a l W r i t e ( 9 , LOW) ;
puts a low voltage on pin 9 to turn it off.
What is the role of the delay command? To find this, comment the delay
command. That is, replace the above delay command with the following and
upload the code.
4.3. Lighting the LED from the Arduino IDE 39
/ / d e l a y ( 2 0 0 0 ) ;
If you observe carefully, you will see that the LED turns blue momentarily and
then turns off.
3. We mentioned earlier that it was possible to light more than one LED simul-
taneously. We will now describe this with another experiment. In this, we will
turn on both blue and red LEDs. We will keep both of them on for 5 seconds
and then turn blue off, leaving only red on. After 3 seconds, we will turn red
also off. This code is given in Arduino Code 4.3. Remember that before writ-
ing either HIGH or LOW on to any pin, its mode has to be declared as OUTPUT,
as given in the code. All the commands in this code are self explanatory.
4. Finally, we will give a hint of how to use the programming capabilities of the
Arduino IDE. For this, we will use Arduino Code 4.4. It makes the LED blink
5 times. Recall from the previous section that a HIGH on pin 10 turns on the
green LED. This cycle is executed for a total of five times. In each iteration,
it will turn the green LED on for a second by giving the HIGH signal and then
turn it off for a second by giving the LOW signal. This cycle is carried out for
a total of 5 times, because of the for loop.
Note: All the above four experiments have been done with the shield affixed to
the Arduino Uno board. One may run these experiments without the shield as well.
But in this case, pin number 13 has to be used in all experiments, as pin 13 lights
up the LED that is on the Arduino Uno board. For example, in Arduino Code 4.1,
one has to replace both occurrences of number 9 with 13. In this case, one will get
the LED of Arduino Uno board light up, as shown in Fig. 4.5.
Note: It should also be pointed out that only one colour is available in Arduino
Uno board. As a result, it is not possible to conduct the experiments that produce
different colours if the shield is not used.
Exercise 4.1 Carry out the following exercise:
1. In Arduino Code 4.2, remove the delay, as discussed above, and check what
happens.
2. Light up all three colours simultaneously, by modifying Arduino Code 4.3.
Change the combination of colours to get different colours.
3. Incorporate some of the features of earlier experiments into Arduino Code 4.4
and come up with different ways of blinking with different colour combina-
tions.
40 4. Interfacing a Light Emitting Diode
Figure 4.5: LED experiments directly on Arduino Uno board, without the shield
4.3.2 Arduino Code
Arduino Code 4.1 Turning on the blue LED. Available at Origin/user-code
/led/arduino/led-blue/led-blue.ino, see Footnote 2 on page 2.
1void s et u p ( ) {
2pi nMo de ( 9 , OUTPUT) ;
3S e r i a l . b eg in ( 1 15 2 00 ) ;
4d i g i t a l W r i t e ( 9 , HIGH) ;
5}
6void l o op ( ) {
7}
Arduino Code 4.2 Turning on the blue LED and turning it off after two seconds.
Available at Origin/user-code/led/arduino/led-blue-delay/led-blu
e-delay.ino, see Footnote 2 on page 2.
1void s et u p ( ) {
2pi nMo de ( 9 , OUTPUT) ;
4.3. Lighting the LED from the Arduino IDE 41
3S e r i a l . b eg in ( 1 15 2 00 ) ;
4d i g i t a l W r i t e ( 9 , HIGH) ;
5de l ay ( 20 00 ) ;
6d i g i t a l W r i t e ( 9 , LOW) ;
7}
8void l o op ( ) {
9}
Arduino Code 4.3 Turning on blue and red LEDs for 5 seconds and then turning
them off one by one. Available at Origin/user-code/led/arduino/led-bl
ue-red/led-blue-red.ino, see Footnote 2 on page 2.
1void s et u p ( ) {
2pi nMo de ( 9 , OUTPUT) ;
3pi nMo de ( 1 1 , OUTPUT) ;
4S e r i a l . b eg in ( 1 15 2 00 ) ;
5d i g i t a l W r i t e ( 9 , HIGH) ;
6d i g i t a l W r i t e ( 1 1 , HIGH) ;
7de l ay ( 50 00 ) ;
8d i g i t a l W r i t e ( 9 , LOW) ;
9de l ay ( 30 00 ) ;
10 d i g i t a l W r i t e ( 1 1 , LOW) ;
11 }
12 void l o op ( ) {
13 }
Arduino Code 4.4 Blinking the green LED. Available at Origin/user-code
/led/arduino/led-green-blink/led-green-blink.ino, see Footnote 2
on page 2.
1int i = 0 ;
2void s et u p ( ) {
3pi nMo de ( 1 0 , OUTPUT) ;
4S e r i a l . b eg in ( 1 15 2 00 ) ;
5for( i = 0 ; i < 5 ; i++)
6{
7d i g i t a l W r i t e ( 1 0 , HIGH) ; / / t u r n t h e LED o n ( HIGH i s t h e v o l t a g e
l e v e l )
8de l ay ( 10 00 ) ; / / w a i t f o r a s e c o n d
9d i g i t a l W r i t e ( 1 0 , LOW) ; // t ur n t h e LED o f f by m a ki ng t h e v o l t a g e
LOW
10 de l ay ( 10 00 ) ; / / w a i t f o r a s e c o n d
11 }
12 }
13 void l o op ( ) {
14 }
42 4. Interfacing a Light Emitting Diode
4.4 Lighting the LED from Python
4.4.1 Lighting the LED
In this section, we discuss how to carry out the experiments of the previous section
from Python. We will list the same four experiments, in the same order. The shield
has to be attached to the Arduino Uno board before doing these experiments and
the Arduino Uno needs to be connected to the computer with a USB cable, as shown
in Fig. 2.4. The reader should go through the instructions given in Sec. 3.2 before
getting started.
1. In the first experiment, we will light up the blue LED on the shield. The
code for this is given in Python Code 4.1. It begins with importing necessary
modules, as given below:
1import o s
2import s y s
Here, os module provides functions for interacting with the operating system.
On the other hand, the sys module provides access to some variables used
or maintained by the interpreter and functions that interact strongly with
the interpreter. Next, the following lines of code are used to get the current
directory followed by splitting it and appending the path to PYTHONPATH
environment:
1cwd = o s . g et c wd ( )
2( s et pa th , Exa mpl es ) = o s . p ath . s p l i t ( cwd )
3sy s . path . a ppe nd ( se tp at h )
After importing the necessary modules, following line imports the Arduino
module from the Python-Arduino toolbox, as explained in Sec. 3.2.3:
1from Arduino . Arduino import Arduino
Next, we will import sleep module, which is a function available in the pack-
age pyserial [13]. For the sake of simplicity, we have configured each experiment
as a class. In Python Code 4.1, we have defined the experiment as class
LED_ON. The following lines of code initilize the parameters and functions
available in this class.
1c l a s s LED_ON:
2d e f __ini t__ ( s e l f , b a u dr a t e ) :
3s e l f . b au dr at e = bau dr at e
4s e l f . s et up ( )
5s e l f . r un ( )
6s e l f . e xi t ( )
4.4. Lighting the LED from Python 43
The function setup creates an object of the Arduino class through which we
can call all the methods available in the base class. Along with this, it locates
the port to which Arduino Uno is connected and opens the port for serial
communication. Thus, we require port number and BAUD RATE for opening
the serial port.
The function run is used to define the functionality of the experiment. In
this experiment, we have to switch on the blue LED. For this, we define the
pin number (which is 9 in this case) and send the required signal to this pin.
Following lines are used to implement this functionality:
1d ef run ( s e l f ) :
2s e l f . b lue = 9
3s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . b lu e , 1 )
At last, the function exit is invoked to close the serial port.
Once all the parameters and functions available in class LED_ON have been
initialized, we create a main method and call it, as given below:
1d e f ma in ( ) :
2obj_ l e d = LED_ON(1 1 52 00 )
3
4i f __name__== ’__main__ ’ :
5ma in ( )
2. Python Code 4.2 does the same thing as what Arduino Code 4.2 does. It does
two more things than what Python Code 4.1 does: It makes the blue LED
light up for two seconds. This is achieved by the command
1s l e e p ( 2 )
The second thing this code does is to turn the blue LED off. This is achieved
by the command
1s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . b lu e , 0 )
As evident, this line of code puts a 0 on pin 9.
3. Python Code 4.3 does the same thing as what Arduino Code 4.3 does. It turns
blue and red LEDs on for five seconds. After that, it turns off blue first. After
3 seconds, it turns off red also. So, when the program ends, no LED is lit up.
4. Python Code 4.4 does exactly what its counterpart in the Arduino IDE does.
It makes the green LED blink five times.
Exercise 4.2 Repeat the exercise of the previous section.
44 4. Interfacing a Light Emitting Diode
4.4.2 Python Code
Python Code 4.1 Turning on the blue LED. Available at Origin/user-code/
led/python/led-blue.py, see Footnote 2 on page 2.
1import os
2import sys
3cwd = o s . g et c wd ( )
4( s et pa th , Exa mpl es ) = o s . p ath . s p l i t ( cwd )
5sy s . path . a ppe nd ( se tp at h )
6
7from Arduino . Arduino import Arduino
8fr om ti me im p or t s l e e p
9
10 c l a s s LED_ON:
11 d e f __ini t__ ( s e l f , b a u dr a t e ) :
12 s e l f . b au dr at e = bau dr at e
13 s e l f . s et up ( )
14 s e l f . r un ( )
15 s e l f . e xi t ( )
16
17 d ef se tu p ( s e l f ) :
18 s e l f . o bj _a rd ui no = Ardui no ( )
19 s e l f . p o rt = s e l f . o bj _ ar d ui n o . l o c a t e p o r t ( )
20 s e l f . o b j_ a r du i n o . o p e n _ s e r i a l ( 1 , s e l f . p or t , s e l f . b au d r a te )
21
22 d ef run ( s e l f ) :
23 s e l f . b lue = 9
24 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . b lu e , 1 )
25
26 d e f e x i t ( s e l f ) :
27 s e l f . o b j_ ar d ui no . c l o s e _ s e r i a l ( )
28
29 d e f ma in ( ) :
30 obj_ l e d = LED_ON(1 1 52 00 )
31
32 i f __name__== ’__main__ ’ :
33 ma in ( )
Python Code 4.2 Turning on the blue LED and turning it off after two sec-
onds. Available at Origin/user-code/led/python/led-blue-delay.p
y, see Footnote 2 on page 2.
1import os
2import sys
3cwd = o s . g et c wd ( )
4( s et pa th , Exa mpl es ) = o s . p ath . s p l i t ( cwd )
5sy s . path . a ppe nd ( se tp at h )
6
4.4. Lighting the LED from Python 45
7from Arduino . Arduino import Arduino
8fr om ti me im p or t s l e e p
9
10 c l a s s LED_ON_OFF:
11 d e f __ini t__ ( s e l f , b a u d r at e ) :
12 s e l f . b au dr at e = bau dr at e
13 s e l f . s et up ( )
14 s e l f . r un ( )
15 s e l f . e xi t ( )
16
17 d ef se tu p ( s e l f ) :
18 s e l f . o bj _a rd ui no = Ardui no ( )
19 s e l f . p o rt = s e l f . o bj _ ar d ui n o . l o c a t e p o r t ( )
20 s e l f . o b j_ a r du i n o . o p e n _ s e r i a l ( 1 , s e l f . p or t , s e l f . b au d r a te )
21
22 d ef run ( s e l f ) :
23 s e l f . b lue = 9
24 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . b lu e , 1 )
25 s l e e p ( 2 )
26 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . b lu e , 0 )
27
28 d e f e x i t ( s e l f ) :
29 s e l f . o b j_ ar d ui no . c l o s e _ s e r i a l ( )
30
31 d e f ma in ( ) :
32 obj_ l e d = LED_ON_OFF(1 15 20 0)
33
34 i f __name__== ’__main__ ’ :
35 ma in ( )
Python Code 4.3 Turning on blue and red LEDs for 5 seconds and then turning
them off one by one. Available at Origin/user-code/led/python/led-blu
e-red.py, see Footnote 2 on page 2.
1import os
2import sys
3cwd = o s . g et c wd ( )
4( s et pa th , Exa mpl es ) = o s . p ath . s p l i t ( cwd )
5sy s . path . a ppe nd ( se tp at h )
6
7from Arduino . Arduino import Arduino
8fr om ti me im p or t s l e e p
9
10 c l a s s LED_ON_OFF_MULTICOLOR:
11
12 d e f __ini t__ ( s e l f , b a u d r at e ) :
13 s e l f . b au dr at e = bau dr at e
14 s e l f . s et up ( )
15 s e l f . r un ( )
46 4. Interfacing a Light Emitting Diode
16 s e l f . e xi t ( )
17
18 d ef se tu p ( s e l f ) :
19 s e l f . o bj _a rd ui no = Ardui no ( )
20 s e l f . p o rt = s e l f . o bj _ ar d ui n o . l o c a t e p o r t ( )
21 s e l f . o b j_ a r du i n o . o p e n _ s e r i a l ( 1 , s e l f . p or t , s e l f . b au d r a te )
22
23 d ef run ( s e l f ) :
24 s e l f . b lue = 9
25 s e l f . g re en = 10
26 s e l f . r ed = 11
27 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . b lu e , s e l f . ba ud ra te )
28 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . red , s e l f . b au dr at e )
29 s l e e p ( 5 )
30 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . b lu e , 0 )
31 s l e e p ( 3 )
32 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . red , 0)
33
34 d e f e x i t ( s e l f ) :
35 s e l f . o b j_ ar d ui no . c l o s e _ s e r i a l ( )
36
37 d e f ma in ( ) :
38 obj_ l e d = LED_ON_OFF_MULTICOLOR(1 15 20 0)
39
40 i f __name__== ’__main__ ’ :
41 ma in ( )
Python Code 4.4 Blinking the green LED. Available at Origin/user-code/l
ed/python/led-green-blink.py, see Footnote 2 on page 2.
1import os
2import sys
3cwd = o s . g et c wd ( )
4( s et pa th , Exa mpl es ) = o s . p ath . s p l i t ( cwd )
5sy s . path . a ppe nd ( se tp at h )
6
7from Arduino . Arduino import Arduino
8fr om ti me im p or t s l e e p
9
10 c l a s s LED_ON_OFF_LOOP:
11
12 d e f __ini t__ ( s e l f , b a u d r at e ) :
13 s e l f . b au dr at e = bau dr at e
14 s e l f . s et up ( )
15 s e l f . r un ( )
16 s e l f . e xi t ( )
17
18 d ef se tu p ( s e l f ) :
19 s e l f . o bj _a rd ui no = Ardui no ( )
4.4. Lighting the LED from Python 47
20 s e l f . p o rt = s e l f . o bj _ ar d ui n o . l o c a t e p o r t ( )
21 s e l f . o b j_ a r du i n o . o p e n _ s e r i a l ( 1 , s e l f . p or t , s e l f . b au d r a te )
22
23 d ef run ( s e l f ) :
24 s e l f . b lue = 9
25 s e l f . g re en = 10
26 s e l f . r ed = 11
27 for i i n r a n ge ( 5 ) :
28 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . g re en , 1 )
29 s l e e p ( 1 )
30 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . g re en , 0 )
31 s l e e p ( 1 )
32
33 d e f e x i t ( s e l f ) :
34 s e l f . o b j_ ar d ui no . c l o s e _ s e r i a l ( )
35
36 d e f ma in ( ) :
37 obj_ l e d = LED_ON_OFF_LOOP( 1 15 2 00 )
38
39 i f __name__== ’__main__ ’ :
40 ma in ( )
41
48 4. Interfacing a Light Emitting Diode
Chapter 5
Interfacing a Pushbutton
A pushbutton is a simple switch which is used to connect or disconnect a circuit. It is
commonly available as a normally open or push to make switch which implies that the
contact is made upon the push or depression of the switch. These switches are widely
used in calculators, computer keyboards, home appliances, push-button telephones
and basic mobile phones, etc. In this chapter, we shall perform an experiment
to read the status of the pushbutton mounted on the shield of the Arduino Uno
board. Advancing further, we shall perform a task depending on the status of the
pushbutton. Digital logic based status monitoring is a very basic and important
task in many industrial applications. This chapter will enable us to have a smooth
hands-on for such functionalities.
5.1 Preliminaries
A pushbutton mounted on the shield is connected to the digital pin 12 of the Arduino
Uno board. The connection diagram for the pushbutton is shown in Fig. 5.1. It has
2 pairs of terminals. Each pair is electrically connected. When the pushbutton is
pressed all the terminals short to complete the circuit, thereby allowing the flow of
current through the switch. As you might expect, there is a limit to the maximum
current that could flow through a pushbutton. This maximum current is also called
the rated current and is usually provided by the manufacturer in the datasheet.
5.2 Connecting a pushbutton with Arduino Uno using a
breadboard
This section is useful for those who either don’t have a shield or don’t want to use
the shield for performing the experiments given in this chapter.
50 5. Interfacing a Pushbutton
Figure 5.1: Internal connection diagram for the pushbutton on the shield
Figure 5.2: A pushbutton to read its status with Arduino Uno using a breadboard
A breadboard is a device for holding the components of a circuit and connect-
ing them together. We can build an electronic circuit on a breadboard without
doing any soldering. To know more about the breadboard and other electronic
components, one should watch the Spoken Tutorials on Arduino as published on
5.2. Connecting a pushbutton with Arduino Uno using a breadboard 51
Figure 5.3: A pushbutton to control an LED with Arduino Uno using a breadboard
https://spoken-tutorial.org/. Ideally, one should go through all the tuto-
rials labeled as Basic. However, we strongly recommend the readers should watch
the fifth and sixth tutorials, i.e., First Arduino Program and Arduino with
Tricolor LED and Push button.
In case you have a pushbutton, and you want to connect it with Arduino Uno on a
breadboard, please refer to Fig. 5.2. The connections given in this figure can be used
to read the status of a pushbutton. As shown in Fig. 5.2, there are three different
wires - red, black, and blue. The red wire is used to connect 5V on Arduino Uno and
one leg of the pushbutton. The black wire connects to one long vertical row on the
side of the breadboard to provide access to the ground (GND) on Arduino Uno. The
blue wire goes from digital pin 12 to one leg of the pushbutton on another side. That
same leg of the pushbutton connects through a pull-down resistor to GND on Arduino
Uno. When the pushbutton is open (unpressed), there is no connection between the
two legs of the pushbutton, so the pin is connected to the ground (through the pull-
down resistor), and we read a LOW on digital pin 12. When the pushbutton is closed
(pressed), it makes a connection between its two legs, connecting the pin to 5V so
that we read a HIGH on digital pin 12.
The connections shown in Fig. 5.3 can be used to control an RGB LED, depending
on the status of the pushbutton. As shown in Fig. 5.3, digital pin 9 on Arduino Uno
52 5. Interfacing a Pushbutton
is connected to the rightmost leg of the RGB LED. Rest of the connections are same
as that in Fig. 5.2.
5.3 Reading the pushbutton status from the Arduino
IDE
5.3.1 Reading the pushbutton status
In this section, we shall describe an experiment that will help to read the status
of a pushbutton through Arduino IDE. Later, we shall change the state of an LED
depending on the status of the pushbutton. The shield has to be attached to the
Arduino Uno board before doing these experiments and the Arduino Uno needs to
be connected to the computer with a USB cable, as shown in Fig. 2.4. The reader
should go through the instructions given in Sec. 3.1 before getting started.
1. In the first experiment, we shall simply read the status of the pushbutton.
Recall that it is a normally open type of switch. So, in an unpressed state,
the logic read will be “0”, corresponding to 0V. And, when the user presses the
pushbutton, the reading would be “1”, corresponding to 5V. The code for this
experiment is given in Arduino Code 5.1. In the initialization part of the code,
we assign the sensor pin to be read, 12 in this case, to a variable for ease. Next,
we initialize the port for serial port communication at data rate of 115200 bits
per second and declare the digital pin 12 as an input pin using the command
pinMode. After initialization, we start reading the status of the pushbutton
using the following command:
1s e n so r V a l u e = d i g i t a l R e a d ( s e n s o r Pi n ) ; / / r e a d p us h −b u t t o n
value
Note that the input argument to this command is the digital pin 12 corre-
sponding to the pin to which the pushbutton is connected. After acquiring the
values, we print them using,
1S e r i a l . p r i n t l n ( s e n so r V al u e ) ; // p r i n t i t a t t he S e r i a l
M o n i t o r
We repeat this read and print process 50 times by putting the commands in a
for loop. While running this experiment, the readers must press and release
the pushbutton and observe the values being printed on the Serial Monitor
of Arduino IDE.
2. In the second experiment, we shall control the power given to an LED as
per the status of the pushbutton. The code for this experiment is given in
5.3. Reading the pushbutton status from the Arduino IDE 53
Arduino Code 5.2. This experiment can be taken as a step further to the
previous one. We declare the LED pin to be controlled as an output pin by,
1pi nMo de ( s e ns o r Pi n , INPUT) ;
Next, we read the pusbhutton value from digital pin 12. If the value is “1”, we
turn on the LED at pin 9 else we turn it off. The condition check is performed
using if else statements. We run these commands for 50 iterations. While
running this experiment, the readers must press and release the pushbutton.
Accordingly, they can observe whether the LED glows when the pushbutton is
pressed.
5.3.2 Arduino Code
Arduino Code 5.1 Read the status of the pushbutton and display it on the Serial
Monitor. Available at Origin/user-code/push/arduino/push-button-st
atus/push-button-status.ino, see Footnote 2 on page 2.
1co nst i nt sensorPin = 12; // D e c l a r e t h e p us h −button
2int sensorValue = 0;
3void s et u p ( ) {
4S e r i a l . b eg in ( 1 15 2 00 ) ;
5pi nMo de ( s e ns o r Pi n , INPUT) ; / / d e c l a r e th e s e n s o r P i n a s a n INPUT
6for (int i = 0 ; i < 5 0 ; i ++){
7s e n so r V a l u e = d i g i t a l R e a d ( s e n s o r Pi n ) ; / / r e a d p us h −b u t t o n v a l u e
8S e r i a l . p r i n t l n ( s e n so r V al u e ) ; // p r i n t i t a t t h e S e r i a l M o n i t o r
9de l ay ( 20 0) ;
10 }
11 }
12 void l o op ( ) {
13 }
Arduino Code 5.2 Turning the LED on or off depending on the pushbutton. Avail-
able at Origin/user-code/push/arduino/led-push-button/led-push
-button.ino, see Footnote 2 on page 2.
1co nst i nt sensorPin = 12;
2co nst i nt le d P i n = 9 ;
3int sensorValue = 0;
4int i ;
5void s et u p ( ) {
6S e r i a l . b eg in ( 1 15 2 00 ) ;
7pi nMo de ( s e ns o r Pi n , INPUT) ;
8pi nMo de ( l e dP in , OUTPUT) ;
9for ( i = 0 ; i < 5 0 ; i ++) {
10 s e n so r V a l u e = d i g i t a l R e a d ( s e n s o r Pi n ) ;
11 S e r i a l . p r i n t l n ( s e n so r V al u e ) ; // p r i n t i t a t t h e S e r i a l M o n i t o r
54 5. Interfacing a Pushbutton
12 i f (sensorValue == 0) {
13 d i g i t a l W r i t e ( l e d Pi n , LOW) ;
14 de l ay ( 20 0) ;
15 }
16 else {
17 d i g i t a l W r i t e ( l e d Pi n , HIGH ) ;
18 de l ay ( 20 0) ;
19 }
20 }
21 }
22 void l o op ( ) {
23 }
5.4 Reading the pushbutton status from Python
5.4.1 Reading the pushbutton status
In this section, we discuss how to carry out the experiments of the previous section
from Python. We will list the same two experiments, in the same order. The shield
has to be attached to the Arduino Uno board before doing these experiments and
the Arduino Uno needs to be connected to the computer with a USB cable, as shown
in Fig. 2.4. The reader should go through the instructions given in Sec. 3.2 before
getting started.
1. In the first experiment, we will read the pushbutton status. The code for this
experiment is given in Python Code 5.1. As explained earlier in Sec. 4.4.1,
we begin with importing necessary modules followed by setting up the serial
port. Then, we read the input coming from digital pin 12 using the following
command:
1v al = s e l f . o bj _a rd ui no . c md _d ig it al _in ( 1 , s e l f . p ush button )
Note that the one leg of the pushbutton on the shield is connected to digital
pin 12 of Arduino Uno as given in Fig. 5.1. The read value is displayed (or
printed) by the following lines:
1for i i n r a n g e ( 2 0 ) :
2v al = s e l f . o bj _a rd ui no . c md _d ig it al _in ( 1 , s e l f . p ush button )
3p r i n t ( v a l )
4s l e e p ( 0 . 5 )
where val contains the pushbutton value acquired by the previous command.
When the pushbutton is not pressed, val will be “0”. On the other hand,
when the pushbutton is pressed, val will be “1”. To encourage the user to
have a good hands-on, we run these commands in a for loop for 20 iterations.
5.4. Reading the pushbutton status from Python 55
The readers are encouraged to change the number of iterations as per their
requirements. While running this experiment, the readers must press and
release the pushbutton and observe the values being printed on the Command
Prompt (on Windows) or Terminal (on Linux), as the case maybe.
2. This experiment is an extension of the previous experiment. Here, we control
the state of an LED as per the status of the pushbutton. In other words, digital
output to an LED is decided by the digital input received from the pushbutton.
The code for this experiment is given in Python Code 5.2. After reading the
pushbutton status, we turn the LED on if the pushbutton is pressed, otherwise
we turn it off. The following lines,
1for i i n r a n g e ( 2 0 ) :
2v al = s e l f . o bj _a rd ui no . c md _d ig it al _in ( 1 , s e l f . p ush button )
3p r i n t ( v a l )
4s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . b lu e , v al )
control the LED state based on the status of the pushbutton. While running
this experiment, the readers must press and release the pushbutton. Accord-
ingly, they can observe whether the LED glows when the pushbutton is pressed.
5.4.2 Python Code
Python Code 5.1 Read the status of the pushbutton and display it on Command
Prompt or the Terminal. Available at Origin/user-code/push/python/pus
h-button-status.py, see Footnote 2 on page 2.
1import os
2import sys
3cwd = o s . g et c wd ( )
4( s et pa th , E xam ples ) = os . p at h . s p l i t ( cwd )
5sy s . path . a ppe nd ( se tp at h )
6
7from Arduino . Arduino import Arduino
8fr om ti me im p or t s l e e p
9
10 c l a s s PUSHBUTTON:
11
12 d e f __ini t__ ( s e l f , b a u d r at e ) :
13 s e l f . b au dr at e = bau dr at e
14 s e l f . s et up ( )
15 s e l f . r un ( )
16 s e l f . e xi t ( )
17
18 d ef se tu p ( s e l f ) :
19 s e l f . o bj _a rd ui no = Ardui no ( )
56 5. Interfacing a Pushbutton
20 s e l f . p o rt = s e l f . o bj _ ar d ui n o . l o c a t e p o r t ( )
21 s e l f . o b j_ a r du i n o . o p e n _ s e r i a l ( 1 , s e l f . p or t , s e l f . b au d r a te )
22
23 d ef run ( s e l f ) :
24 s e l f . p us hb ut ton = 12
25 for i i n r a n g e ( 2 0 ) :
26 v al = s e l f . o bj _a rd ui no . c md _d ig it al _in ( 1 , s e l f . p ush button )
27 p r i n t ( v a l )
28 s l e e p ( 0 . 5 )
29
30 d e f e x i t ( s e l f ) :
31 s e l f . o b j_ ar d ui no . c l o s e _ s e r i a l ( )
32
33 d e f ma in ( ) :
34 obj _ p u s h b u t t o n = PUSHBUTTON(1 1 5 20 0)
35
36 i f __name__== ’__main__ ’ :
37 ma in ( )
Python Code 5.2 Turning the LED on or off depending on the pushbutton. Avail-
able at Origin/user-code/push/python/led-push-button.py, see Foot-
note 2 on page 2.
1import os
2import sys
3cwd = o s . g et c wd ( )
4( s et pa th , E xam ples ) = os . p at h . s p l i t ( cwd )
5sy s . path . a ppe nd ( se tp at h )
6
7from Arduino . Arduino import Arduino
8fr om ti me im p or t s l e e p
9
10 c l a s s PUSHBUTTON_LED :
11
12 d e f __ini t__ ( s e l f , b a u d r at e ) :
13 s e l f . b au dr at e = bau dr at e
14 s e l f . s et up ( )
15 s e l f . r un ( )
16 s e l f . e xi t ( )
17
18 d ef se tu p ( s e l f ) :
19 s e l f . o bj _a rd ui no = Ardui no ( )
20 s e l f . p o rt = s e l f . o bj _ ar d ui n o . l o c a t e p o r t ( )
21 s e l f . o b j_ a r du i n o . o p e n _ s e r i a l ( 1 , s e l f . p or t , s e l f . b au d r a te )
22
23 d ef run ( s e l f ) :
24 s e l f . b lue = 9
25 s e l f . g re en = 10
26 s e l f . r ed = 11
5.4. Reading the pushbutton status from Python 57
27 s e l f . p us hb ut ton = 12
28 for i i n r a n g e ( 2 0 ) :
29 v al = s e l f . o bj _a rd ui no . c md _d ig it al _in ( 1 , s e l f . p ush button )
30 p r i n t ( v a l )
31 s e l f . o bj _a rd ui no . c md _digital_out ( 1 , s e l f . b lu e , v al )
32 s l e e p ( 0 . 5 )
33
34 d e f e x i t ( s e l f ) :
35 s e l f . o b j_ ar d ui no . c l o s e _ s e r i a l ( )
36
37 d e f ma in ( ) :
38 obj _ p u s h b u t t o n = PUSHBUTTON_LED( 1 15 20 0)
39
40 i f __name__== ’__main__ ’ :
41 ma in ( )
58 5. Interfacing a Pushbutton
Chapter 6
Interfacing a Light Dependent
Resistor
A Light Dependent Resistor (LDR) or Photoresistor is a light sensitive semiconductor
device whose resistance varies with the variation in the intensity of light falling on
it. As the intensity of the incident light increases, resistance offered by the LDR
decreases. Typically, in dark, the resistance offered by an LDR is in the range of a
few mega ohms. With the increase in light intensity, the resistance reduces to as low
as a few ohms.
An LDR is widely used in camera shutter control, light intensity meters, burglar
alarms, street lighting control, automatic emergency lights, etc. In this chapter we
shall interface an LDR with the Arduino Uno board.
6.1 Preliminaries
A typical LDR and its symbolic representation are shown in Fig. 6.1a and Fig. 6.1b
respectively. The shield provided with the kit has an LDR mounted on it. The
LDR mounted on the shield looks exactly like the picture in Fig. 6.1a, although, the
picture looks a lot larger. This LDR is connected to the analog pin 5 of the Arduino
Uno board. The connections for this experiment are shown in Fig. 6.2. However,
the user doesn’t need to connect any wire or component explicitly.
The LDR mounted on the shield is an analog sensor. Hence, the analog voltage,
corresponding to the changing resistance, across its terminals needs to be digitized
before being sent to the computer. This is taken care of by an onboard Analog to
Digital Converter (ADC) of ATmega328 microcontroller on the Arduino Uno board.
ATmega328 has a 6-channel, 0 through 5, 10 bit ADC. Analog pin 5 of the Arduino
Uno board, to which the LDR is connected, corresponds to channel 5 of the ADC.
60 6. Interfacing a Light Dependent Resistor
(a) Pictorial representation of an LDR (b) Symbolic representation of an LDR
Figure 6.1: Light Dependent Resistor
Figure 6.2: Internal connection diagram for the LDR on the shield
As there are 10 bits, 0-5V readings from LDR are mapped to the ADC values from
0 to 1023.
LDR is a commonly available sensor in the market. It costs about Rs. 100.
There are multiple manufacturers which provide commercial LDRs. Some exam-
ples are VT90N1 and VT935G from EXCELITAS TECH, and N5AC501A085 and
NSL19M51 from ADVANCED PHOTONIX.
6.2. Connecting an LDR with Arduino Uno using a breadboard 61
Figure 6.3: An LDR to read its values with Arduino Uno using a breadboard
6.2 Connecting an LDR with Arduino Uno using a bread-
board
This section is useful for those who either don’t have a shield or don’t want to use
the shield for performing the experiments given in this chapter.
A breadboard is a device for holding the components of a circuit and connect-
ing them together. We can build an electronic circuit on a breadboard without
doing any soldering. To know more about the breadboard and other electronic
components, one should watch the Spoken Tutorials on Arduino as published on
https://spoken-tutorial.org/. Ideally, one should go through all the tuto-
rials labeled as Basic. However, we strongly recommend the readers should watch
the fifth and sixth tutorials, i.e., First Arduino Program and Arduino with
Tricolor LED and Push button.
In case you have an LDR, and you want to connect it with Arduino Uno on a
breadboard, please refer to Fig. 6.3. The connections given in this figure can be used
to read the voltage values from an LDR connected to the analog pin 5 on Arduino
Uno board. As shown in Fig. 6.3, one leg of the LDR is connected to 5V on Arduino
Uno and the other leg to the analog pin 5 on Arduino Uno. A resistor is also
connected to the same leg and grounded. From Fig. 6.2 and Fig. 6.3, one can infer
that a resistor along with the LDR is used to create a voltage divider circuit. The
varying resistance of the LDR is converted to a varying voltage. Finally, this voltage
is used by the analog pin 5 of Arduino Uno in its logic.
The connections shown in Fig. 6.4 can be used to control an RGB LED, depending
62 6. Interfacing a Light Dependent Resistor
Figure 6.4: An LDR to control an LED with Arduino Uno using a breadboard
on the voltage values from the LDR. As shown in Fig. 6.4, digital pin 11 on Arduino
Uno is connected to the leftmost leg of the RGB LED. Rest of the connections are
same as that in Fig. 6.3.
6.3 Interfacing the LDR through the Arduino IDE
6.3.1 Interfacing the LDR
In this section, we shall describe an experiment that will help to read the voltage
values from an LDR connected to the analog pin 5 of the Arduino Uno board. Later,
the read values will be used to change the state of an LED. The shield has to be
attached to the Arduino Uno board before doing these experiments and the Arduino
Uno needs to be connected to the computer with a USB cable, as shown in Fig. 2.4.
The reader should go through the instructions given in Sec. 3.1 before getting started.
1. A simple code to read the LDR values is given in Arduino Code 6.1. As
discussed earlier, the 0-5V LDR readings are mapped to 0-1023 through an
ADC. The Arduino IDE based command for the analog read functionality is
given by,
1v a l = a na l og R e ad ( A5) ; / / v a l u e o f LDR
6.3. Interfacing the LDR through the Arduino IDE 63
where A5 represents the analog pin 5 to be read and the read LDR values are
stored in the variable val. The read values are then displayed using,
1S e r i a l . p r i n t l n ( v a l ) ; / / f o r d i s p l a y
The delay in the code
1de l ay ( 50 0) ;
is added so that the readings do not scroll away very fast. The entire reading
and display operation is carried out 50 times.
To observe the values, one has to open the Serial Monitor of the Arduino
IDE. The numbers displayed are in the range 0 to 1023 and depend on the light
falling on the LDR. If one does the experiment in a completely dark room, the
reading will be 0. If on the other hand, a bright light, say for instance the torch
light from mobile, is shined, the value displayed is close to 1023. One will get
intermediate values by keeping one’s finger on the LDR. While running this
experiment, the readers must keep their fingertips on the LDR and observe the
change in values being printed on the Serial Monitor of Arduino IDE.
2. This experiment is an extension of the previous experiment. Here, depending
the resistance of the LDR, we will turn the red LED on. The program for
this is available at Arduino Code 6.2. The value of LDR is read and stored
in val. In case it is below some threshold (like 300 in Arduino Code 6.2), it
puts a high in pin number 11. From Sec. 4.1, one can note that this pin is for
the red LED. If the LDR value is below 300, the red LED will be on, else, it
will be turned off. While running this experiment, the readers must keep their
fingertips on the LDR so that the threshold is achieved. Accordingly, they can
observe whether the red LED is turned on.
Exercise 6.1 Carry out the following exercise:
1. Carry out the experiment in a dark room and check what values get displayed
on the Serial Monitor.
2. Carry out the experiment with the torch light from the mobile phone shining
on the LDR.
64 6. Interfacing a Light Dependent Resistor
6.3.2 Arduino Code
Arduino Code 6.1 Read and display the LDR values. Available at Origin/use
r-code/ldr/arduino/ldr-read/ldr-read.ino, see Footnote 2 on page 2.
1int v a l ; // f o r LDR
2int i = 1 ;
3void s et u p ( ) {
4S e r i a l . b eg in ( 1 15 2 00 ) ;
5for( i = 1 ; i <= 5 0 ; i ++){
6v a l = a na l og R e ad ( A5) ; / / v a l u e o f LDR
7S e r i a l . p r i n t l n ( v a l ) ; / / f o r d i s p l a y
8de l ay ( 50 0) ;
9}
10 }
11 void l o op ( ) {
12 }
Arduino Code 6.2 Turning the red LED on and off. Available at Origin/user
-code/ldr/arduino/ldr-led/ldr-led.ino, see Footnote 2 on page 2.
1int v a l ;
2int i = 1 ;
3void s et u p ( ) {
4pi nMo de ( 1 1 , OUTPUT) ; // LED Pi n
5S e r i a l . b eg in ( 1 15 2 00 ) ;
6for( i = 1 ; i <= 5 0 ; i ++){
7v a l = a na l og R e ad ( A5) ; / / V a l u e o f LDR
8S e r i a l . p r i n t l n ( v a l ) ;
9i f ( v a l < 30 0 ) { // Threshold
10 d i g i t a l W r i t e ( 1 1 , HIGH) ;
11 }
12 else
13 {
14 d i g i t a l W r i t e ( 1 1 , LOW) ;
15 }
16 de l ay ( 50 0) ;
17 }
18 }
19 void l o op ( ) {
20 }
6.4 Interfacing the LDR through Python
6.4.1 Interfacing the LDR
In this section, we discuss how to carry out the experiments of the previous section
from Python. We will list the same two experiments, in the same order. The shield
6.4. Interfacing the LDR through Python 65
has to be attached to the Arduino Uno board before doing these experiments and
the Arduino Uno needs to be connected to the computer with a USB cable, as shown
in Fig. 2.4. The reader should go through the instructions given in Sec. 3.2 before
getting started.
1. In the first experiment, we will read the LDR values. The code for this exper-
iment is given in Python Code 6.1. As explained earlier in Sec. 4.4.1, we begin
with importing necessary modules followed by setting up the serial port. Then,
we read the input coming from analog pin 5 using the following command:
1v al = s e l f . o bj _a rd ui no . c md_anal og_in ( 1 , s e l f . l d r )
Note that the one leg of the LDR on the shield is connected to analog pin 5 of
Arduino Uno as given in Fig. 6.2. The read value is displayed by the following
command:
1p r i n t ( v a l )
where val contains the LDR values ranging from 0 to 1023. If one does the
experiment in a completely dark room, the reading will be 0. If on the other
hand, a bright light, say for instance the torch light from mobile, is shined, the
value displayed is close to 1023. One will get intermediate values by keeping
one’s finger on the LDR. To encourage the user to have a good hands-on,
we run these commands in a for loop for 50 iterations. While running this
experiment, the readers must keep their fingertips on the LDR and observe the
change in values being printed on on the Command Prompt (on Windows) or
Terminal (on Linux), as the case maybe.
2. This experiment is an extension of the previous experiment. Here, depending
the resistance of the LDR, we will turn the red LED on. The program for
this is available at Python Code 6.2. The value of LDR is read and stored
in val. In case it is below some threshold (like 300 in Python Code 6.2), it
puts a high in pin number 11. From Sec. 4.1, one can note that this pin is for
the red LED. If the LDR value is below 300, the red LED will be on, else, it
will be turned off. While running this experiment, the readers must keep their
fingertips on the LDR so that the threshold is achieved. Accordingly, they can
observe whether the red LED is turned on.
Exercise 6.2 Carry out the exercise below:
1. Carry out the exercise in the previous section.
2. Calculate the difference in LDR readings in indoor room before lighting the
lamp and after lighting the lamp. You can also record changes in the room
lighting at different times of the day.
66 6. Interfacing a Light Dependent Resistor
6.4.2 Python Code
Python Code 6.1 Read and display the LDR values. Available at Origin/user
-code/ldr/python/ldr-read.py, see Footnote 2 on page 2.
1import os
2import sys
3cwd = o s . g et c wd ( )
4( s et pa th , E xam ples ) = os . p at h . s p l i t ( cwd )
5sy s . path . a ppe nd ( se tp at h )
6
7from Arduino . Arduino import Arduino
8fr om ti me im p or t s l e e p
9
10 c l a s s LDR:
11 d e f __ini t__ ( s e l f , b a u dr a t e ) :
12 s e l f . b au dr at e = bau dr at e
13 s e l f . s et up ( )
14 s e l f . r un ( )
15 s e l f . e xi t ( )
16
17 d ef se tu p ( s e l f ) :
18 s e l f . o bj _a rd ui no = Ardui no ( )
19 s e l f . p o rt = s e l f . o bj _ ar d ui n o . l o c a t e p o r t ( )
20 s e l f . o b j_ a r du i n o . o p e n _ s e r i a l ( 1 , s e l f . p or t , s e l f . b au d r a te )
21
22 d ef run ( s e l f ) :
23 s e l f . l dr = 5
24 for i i n r a n g e ( 5 0 ) :
25 v al = s e l f . o bj _a rd ui no . c md_anal og_in ( 1 , s e l f . l d r )
26 p r i n t ( v a l )
27 s l e e p ( 0 . 5 )
28
29 d e f e x i t ( s e l f ) :
30 s e l f . o b j_ ar d ui no . c l o s e _ s e r i a l ( )
31
32 d e f ma in ( ) :
33 ob j _ l dr = LDR( 1 15 2 00 )
34
35 i f __name__== ’__main__ ’ :
36 ma in ( )
Python Code 6.2 Turning the red LED on and off. Available at Origin/user-
code/ldr/python/ldr-led.py, see Footnote 2 on page 2.
6.4. Interfacing the LDR through Python 67
1import os
2import sys
3cwd = o s . g et c wd ( )
4( s et pa th , E xam ples ) = os . p at h . s p l i t ( cwd )
5sy s . path . a ppe nd ( se tp at h )
6
7from Arduino . Arduino import Arduino
8fr om ti me im p or t s l e e p
9
10 c l a s s LDR:
11 d e f __ini t__ ( s e l f , b a u d r at e ) :
12 s e l f . b au dr at e = bau dr at e
13 s e l f . s et up ( )
14 s e l f . r un ( )
15 s e l f . e xi t ( )
16
17 d ef se tu p ( s e l f ) :
18 s e l f . o bj _a rd ui no = Ardui no ( )
19 s e l f . p o rt = s e l f . o bj _ ar d ui n o . l o c a t e p o r t ( )
20 s e l f . o b j_ a r du i n o . o p e n _ s e r i a l ( 1 , s e l f . p or t , s e l f . b au d r a te )
21
22 d ef run ( s e l f ) :
23 s e l f . l dr = 5
24 s e l f . b lue = 9
25 s e l f . g re en = 10
26 s e l f . r ed = 11
27 for i i n r a n g e ( 5 0 ) :
28 v al = s e l f . o bj _a rd ui no . c md_anal og_in ( 1 , s e l f . l d r )
29 p r i n t ( v a l )
30 i f in t ( v a l )