0% found this document useful (0 votes)
22 views

Scilab

This document provides an introduction to microcontroller programming using Arduino, Scilab and Xcos. It covers the hardware environment including microcontrollers, Arduino boards and shields. It also discusses how to communicate between the software and Arduino and includes examples of interfacing common sensors and components like LEDs, pushbuttons, LDRs, potentiometers and thermistors.

Uploaded by

Prueba Armonía
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Scilab

This document provides an introduction to microcontroller programming using Arduino, Scilab and Xcos. It covers the hardware environment including microcontrollers, Arduino boards and shields. It also discusses how to communicate between the software and Arduino and includes examples of interfacing common sensors and components like LEDs, pushbuttons, LDRs, potentiometers and thermistors.

Uploaded by

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

Microcontroller Programming

with Arduino, Scilab, and Xcos

Sudhakar Kumar, Manas Ranjan Das


Rajesh Kushalkar, Nirmala Venkat
Inderpreet Arora, Samrudh Kelkar, Srikant Patnaik
Rupak Rokade, Tanmayee Joshi, Kiranmayee Madhusudan
Paavni Shukla, Sonal Singh
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

Preface vii

List of Figures ix

List of Tables xiii

List of Arduino Code xv

List of Scilab Code xvii

List of Acronyms xix

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 Brief History . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Arduino IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.1.1 Downloading and installing on Windows . . . . . . . . . . . . 20
3.1.2 Downloading and installing on GNU/Linux Ubuntu . . . . . . 21
iv Contents

3.1.3 Arduino Development Environment . . . . . . . . . . . . . . . 23


3.1.4 Testing Arduino with a sample program . . . . . . . . . . . . 26
3.1.5 FLOSS Firmware . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.2 Scilab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.2.1 Downloading and installing on Windows . . . . . . . . . . . . 28
3.2.2 Downloading and installing on GNU/Linux Ubuntu . . . . . . 28
3.2.3 Scilab-Arduino toolbox . . . . . . . . . . . . . . . . . . . . . . 29
3.2.4 Identifying Arduino communication port number . . . . . . . 31
3.2.5 Testing Scilab-Arduino toolbox . . . . . . . . . . . . . . . . . 33
3.2.6 Firmware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.3 Xcos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.3.1 Downloading, installing and testing . . . . . . . . . . . . . . . 37
3.3.2 Use case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.3.3 Xcos-Arduino . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

4 Interfacing a Light Emitting Diode 45


4.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.2 Connecting an RGB LED with Arduino Uno using a breadboard . . 47
4.3 Lighting the LED from the Arduino IDE . . . . . . . . . . . . . . . . 48
4.3.1 Lighting the LED . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.3.2 Arduino Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.4 Lighting the LED from Scilab . . . . . . . . . . . . . . . . . . . . . . 52
4.4.1 Lighting the LED . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.4.2 Scilab Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.5 Lighting the LED from Scilab Xcos . . . . . . . . . . . . . . . . . . . 54

5 Interfacing a Pushbutton 59
5.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.2 Connecting a pushbutton with Arduino Uno using a breadboard . . . 59
5.3 Reading the pushbutton status from the Arduino IDE . . . . . . . . 62
5.3.1 Reading the pushbutton status . . . . . . . . . . . . . . . . . 62
5.3.2 Arduino Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.4 Reading the pushbutton Status from Scilab . . . . . . . . . . . . . . 64
5.4.1 Reading the pushbutton Status . . . . . . . . . . . . . . . . . 64
5.4.2 Scilab Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.5 Accessing the pushbutton from Xcos . . . . . . . . . . . . . . . . . . 66

6 Interfacing a Light Dependent Resistor 71


6.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.2 Connecting an LDR with Arduino Uno using a breadboard . . . . . 73
Contents v

6.3 Interfacing the LDR through the Arduino IDE . . . . . . . . . . . . 74


6.3.1 Interfacing the LDR . . . . . . . . . . . . . . . . . . . . . . . 74
6.3.2 Arduino Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.4 Interfacing the LDR through Scilab . . . . . . . . . . . . . . . . . . . 76
6.4.1 Interfacing the LDR . . . . . . . . . . . . . . . . . . . . . . . 76
6.4.2 Scilab Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.5 Interfacing the LDR through Xcos . . . . . . . . . . . . . . . . . . . 78

7 Interfacing a Potentiometer 83
7.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.2 Connecting a potentiometer with Arduino Uno using a breadboard . 84
7.3 Reading the potentiometer from the Arduino IDE . . . . . . . . . . . 85
7.3.1 Reading the potentiometer . . . . . . . . . . . . . . . . . . . . 85
7.3.2 Arduino Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.4 Reading the potentiometer from Scilab . . . . . . . . . . . . . . . . . 87
7.4.1 Reading the potentiometer . . . . . . . . . . . . . . . . . . . . 87
7.4.2 Scilab Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.5 Reading the potentiometer from Xcos . . . . . . . . . . . . . . . . . 89

8 Interfacing a Thermistor 91
8.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
8.2 Connecting a thermistor with Arduino Uno using a breadboard . . . 93
8.3 Interfacing the thermistor from the Arduino IDE . . . . . . . . . . . 94
8.3.1 Interfacing the thermistor . . . . . . . . . . . . . . . . . . . . 94
8.3.2 Arduino Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
8.4 Interfacing the thermistor from Scilab . . . . . . . . . . . . . . . . . 98
8.4.1 Interfacing the thermistor . . . . . . . . . . . . . . . . . . . . 98
8.4.2 Scilab Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
8.5 Interfacing the thermistor from Xcos . . . . . . . . . . . . . . . . . . 101

9 Interfacing a Servomotor 107


9.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2 Connecting a servomotor with Arduino Uno using a breadboard . . . 108
9.3 Controlling the servomotor through the Arduino IDE . . . . . . . . . 109
9.3.1 Controlling the servomotor . . . . . . . . . . . . . . . . . . . 109
9.3.2 Arduino Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.4 Controlling the servomotor through Scilab . . . . . . . . . . . . . . . 114
9.4.1 Controlling the servomotor . . . . . . . . . . . . . . . . . . . 114
9.4.2 Scilab Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
9.5 Controling the servomotor through Xcos . . . . . . . . . . . . . . . . 117
vi Contents

10 Interfacing a DC Motor 123


10.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
10.2 Controlling the DC motor from Arduino . . . . . . . . . . . . . . . . 125
10.2.1 Controlling the DC motor . . . . . . . . . . . . . . . . . . . . 125
10.2.2 Arduino Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
10.3 Controlling the DC motor from Scilab . . . . . . . . . . . . . . . . . 129
10.3.1 Controlling the DC motor . . . . . . . . . . . . . . . . . . . . 129
10.3.2 Scilab Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
10.4 Controlling the DC motor from Xcos . . . . . . . . . . . . . . . . . . 133

11 Implementation of Modbus Protocol 139


11.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
11.1.1 Energy meter . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
11.1.2 Endianness . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
11.2 Setup for the experiment . . . . . . . . . . . . . . . . . . . . . . . . . 146
11.3 Software required for this experiment . . . . . . . . . . . . . . . . . . 147
11.3.1 Arduino Firmware . . . . . . . . . . . . . . . . . . . . . . . . 149
11.4 Manifestation of Modbus protocol through Scilab . . . . . . . . . . . 149
11.5 Reading the electrical parameters from Scilab . . . . . . . . . . . . . 151
11.5.1 Reading the electrical parameters . . . . . . . . . . . . . . . . 151
11.5.2 Scilab Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
11.5.3 Output in the Scilab Console . . . . . . . . . . . . . . . . . . 153
11.6 Reading the electrical parameters from Xcos . . . . . . . . . . . . . . 154

A Procuring the Hardware 159

References 161
Preface

Microcontrollers are extensively used in the industry, automobiles and home ap-
pliances, to list a few. Arduino is a popular open source microcontroller available
today. Arduino comes with its own software, Arduino IDE, short for Integrated De-
velopment Environment. Using Arduino IDE, one can program Arduino for different
purposes. Some times, one may want to program Arduino using high level program-
ming languages. We have explained Arduino programming with the following high
level languages through separate books.
1 Scilab and Xcos: Microcontroller programming with Arduino, Scilab,
and Xcos
2 Python: Microcontroller programming with Arduino and
Python
3 OpenModelica: Microcontroller programming with Arduino and Open-
Modelica
4 Julia: Microcontroller programming with Arduino and Julia
Each of these four books concentrates on one topic. Such a compact book may
be of interest to those who are interested in only one programming language. We
are bringing out a fifth book that combines all of these languages for the benefit of
readers who may be interested in two or more languages.
All code explained in the book are made freely downloadable and their URL are
provided at appropriate places. The user will need the Arduino Uno board and a
Shield to carry out the experiments explained in this book. It is easy to procure
Arduino UNO, which is available through many vendors. The location of the Gerber
file and details of the components required to assemble the Shield are provided in
the book. Alternatively, one can buy the Shield directly from vendors, details of
whom are also provided in the book.
This work is supported by the FOSSEE (Free/Libre and Open Source Software
for Education) project (https://fossee.in) at IIT Bombay. This project is
funded by the National Mission on Education through ICT, Ministry of Education,
Govt. of India. FOSSEE promotes software, such as Scilab, Python, eSim, Open-

vii
viii Contents

FOAM, OpenModelica, DWSIM, Osdag, R, GIMP, Blender, Inkscape, ChemCollec-


tive Virtual Lab, and Jmol. It trains students on these software to the level they can
contribute, curates such contributions, and releases them to the public. It also con-
ducts various competitions/hackathons/marathons, handholds the motivated who
need help, and recognises the best contributions. Students who have participated in
FOSSEE projects have benefited in terms of internship, employment, and admission
to higher studies with schloarship.
The FOSSEE project provides support to the Arduino activity through the web-
site https://floss-arduino.fossee.in/. It has a lot of useful information,
such as Spoken Tutorials, and links to download soft copies of these books. We invite
the learners to try out these books and give their feedback.

Kannan Moudgalya
IIT Bombay
2 October 2022
List of Figures

2.1 Functional block diagram of a microcontroller . . . . . . . . . . . . . 4


2.2 ADC resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 The logo of Open Source Hardware . . . . . . . . . . . . . . . . . . . 7
2.4 Arduino Uno Board . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.5 Arduino Mega Board . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.6 LilyPad Arduino Board . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.7 Arduino Phone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.8 3D printer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.9 PCB image of the shield . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.10 Pictorial representation of the schematic of the shield . . . . . . . . . 14
2.11 PCB of the shield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Arduino IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.6 Linux terminal to launch Scilab . . . . . . . . . . . . . . . . . . . . . 29
3.7 Browsing toolbox directory . . . . . . . . . . . . . . . . . . . . . . . 30
3.8 Output of builder.sce . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.9 Output of loader.sce . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.10 Device Manager in windows . . . . . . . . . . . . . . . . . . . . . . . 33
3.11 COM port properties window . . . . . . . . . . . . . . . . . . . . . . 34
3.12 Port number on Linux terminal . . . . . . . . . . . . . . . . . . . . . 34
3.13 Scilab test code output . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.14 Arduino toolbox functions used in this book . . . . . . . . . . . . . . 36
3.15 Sine generator in palette browser . . . . . . . . . . . . . . . . . . . . 38
3.16 CSCOPE block in xcos . . . . . . . . . . . . . . . . . . . . . . . . . . 39

ix
x List of Figures

3.17 CLOCK_c block in xcos . . . . . . . . . . . . . . . . . . . . . . . . . 39


3.18 Sine generator in Xcos . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.19 Sine generator Xcos output . . . . . . . . . . . . . . . . . . . . . . . 40
3.20 CSCOPE configuration window . . . . . . . . . . . . . . . . . . . . . 41
3.21 Simulation setup window . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.22 Palette browser showing Arduino blocks . . . . . . . . . . . . . . . . 42
3.23 Xcos block help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

4.1 Light Emitting Diode . . . . . . . . . . . . . . . . . . . . . . . . . . . 45


4.2 Internal connection diagram for the RGB LED on the shield . . . . . 46
4.3 Connecting Arduino Uno and shield . . . . . . . . . . . . . . . . . . 46
4.4 An RGB LED with Arduino Uno using a breadboard . . . . . . . . . 47
4.5 LED experiments directly on Arduino Uno board, without the shield 50
4.6 Turning the blue LED on through Xcos . . . . . . . . . . . . . . . . 55
4.7 Turning the blue LED on through Xcos for two seconds . . . . . . . 56
4.8 Turning the blue and red LEDs on through Xcos and turning them
off one by one . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.9 Blinking the green LED every second through Xcos . . . . . . . . . . 58

5.1 Internal connection diagram for the pushbutton on the shield . . . . 60


5.2 A pushbutton to read its status with Arduino Uno using a breadboard 60
5.3 A pushbutton to control an LED with Arduino Uno using a breadboard 61
5.4 GUI in Scilab to show the status of the pushbutton . . . . . . . . . . 65
5.5 Printing the push button status on the display block . . . . . . . . . 67
5.6 Turning the LED on or off, depending on the pushbutton . . . . . . 68

6.1 Light Dependent Resistor . . . . . . . . . . . . . . . . . . . . . . . . 72


6.2 Internal connection diagram for the LDR on the shield . . . . . . . . 72
6.3 An LDR to read its values with Arduino Uno using a breadboard . . 73
6.4 An LDR to control an LED with Arduino Uno using a breadboard . 74
6.5 Xcos diagram to read LDR values . . . . . . . . . . . . . . . . . . . . 79
6.6 Plot window in Xcos to read LDR values . . . . . . . . . . . . . . . . 79
6.7 Xcos diagram to read the value of the LDR, which is used to turn the
blue LED on or off . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.8 Plot window in Xcos to read LDR values and the state of LED . . . 81

7.1 Potentiometer’s schematic on the shield . . . . . . . . . . . . . . . . 84


7.2 A potentiometer to control an LED with Arduino Uno using a bread-
board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.3 Turning LEDs on through Xcos depending on the potentiometer thresh-
old . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
List of Figures xi

8.1 Pictorial and symbolic representation of a thermistor . . . . . . . . . 92


8.2 Internal connection diagrams for thermistor and buzzer on the shield 92
8.3 A thermistor to read its values with Arduino Uno using a breadboard 93
8.4 A thermistor to control a buzzer with Arduino Uno using a breadboard 94
8.5 Xcos diagram to read thermistor values . . . . . . . . . . . . . . . . 102
8.6 Plot window in Xcos to read thermistor values . . . . . . . . . . . . . 103
8.7 Xcos diagram to read the value of thermistor, which is used to turn
the buzzer on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.8 Plot window in Xcos to read thermistor values and the state of LED 105

9.1 Connecting servomotor to the shield attached on Arduino Uno . . . . 108


9.2 A servomotor with Arduino Uno using a breadboard . . . . . . . . . 109
9.3 A servomotor and a potentiometer with Arduino Uno using a bread-
board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
9.4 Rotating the servomotor by a fixed angle . . . . . . . . . . . . . . . . 118
9.5 Rotating the servomotor forward and then reverse . . . . . . . . . . 119
9.6 Rotating the servomotor in increments of 20◦ . . . . . . . . . . . . . 120
9.7 Rotating the servomotor as suggested by the potentiometer . . . . . 121

10.1 L293D motor driver board . . . . . . . . . . . . . . . . . . . . . . . . 124


10.2 PWM pins on an Arduino Uno board . . . . . . . . . . . . . . . . . . 125
10.3 A schematic of DC motor connections . . . . . . . . . . . . . . . . . 126
10.4 How to connect the DC motor to the Arduino Uno board . . . . . . 126
10.5 Control of DC motor for a specified time from Xcos . . . . . . . . . . 134
10.6 Xcos control of the DC motor in forward and reverse directions . . . 135
10.7 Xcos control of the DC motor in both directions in a loop . . . . . . 136

11.1 Block diagram representation of the Protocol . . . . . . . . . . . . . 140


11.2 Cycle of query-response between master and slave . . . . . . . . . . . 140
11.3 Pins in RS485 module . . . . . . . . . . . . . . . . . . . . . . . . . . 141
11.4 Block diagram for reading the parameters in energy meter . . . . . . 146
11.5 Experimental set up for reading energy meter . . . . . . . . . . . . . 147
11.6 Flowchart of Arduino firmware . . . . . . . . . . . . . . . . . . . . . 148
11.7 Flowchart of the steps happening in the FLOSS code . . . . . . . . . 150
11.8 Single phase current output on Scilab Console . . . . . . . . . . . . . 153
11.9 Single phase current output in energy meter . . . . . . . . . . . . . . 154
11.10Single phase voltage output on Scilab Console . . . . . . . . . . . . . 154
11.11Single phase voltage output in energy meter . . . . . . . . . . . . . . 155
11.12Single phase active power output on Scilab Console . . . . . . . . . . 155
11.13Single phase active power output in energy meter . . . . . . . . . . . 156
xii List of Figures

11.14Xcos diagram to read energy meter values . . . . . . . . . . . . . . . 156


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

4.1 Parameters to light the blue LED in Xcos . . . . . . . . . . . . . . . 55


4.2 Parameters to light the blue LED in Xcos for two seconds . . . . . . 56
4.3 Parameters to turn the blue and red LEDs on and then turn them off
one by one . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.4 Parameters to make the green LED blink every second . . . . . . . . 58

5.1 Parameters to print the push button status on the display block . . . 67
5.2 Xcos parameters to turn the LED on through the pushbutton . . . . 68

6.1 Xcos parameters to read LDR . . . . . . . . . . . . . . . . . . . . . . 80


6.2 Xcos parameters to read LDR and regulate blue LED . . . . . . . . . 82

7.1 Xcos parameters to turn on different LEDs depending on the poten-


tiometer value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

8.1 Xcos parameters to read thermistor . . . . . . . . . . . . . . . . . . . 102


8.2 Xcos parameters to read thermistor and switch the buzzer . . . . . . 104

9.1 Connecting a typical servomotor to Arduino Uno board . . . . . . . 108


9.2 Parameters to rotate the servomotor by 30◦ . . . . . . . . . . . . . . 117
9.3 Parameters to rotate the servomotor forward and reverse . . . . . . . 118
9.4 Parameters to make the servomotor to sweep the entire range in in-
crements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
9.5 Parameters to rotate the servomotor based on the input from the
potentiometer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

xiii
xiv List of Tables

10.1 Values to be passed for different H-Bridge circuits . . . . . . . . . . . 124


10.2 Xcos parameters to drive the DC motor for a specified time . . . . . 134
10.3 Xcos parameters to drive the DC motor in forward and reverse direc-
tions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
10.4 Xcos parameters to drive the DC motor in a loop . . . . . . . . . . . 137

11.1 Pins available on RS485 and their usage . . . . . . . . . . . . . . . . 141


11.2 Operations supported by Modbus RTU . . . . . . . . . . . . . . . . . 142
11.3 Individual parameter address in EM6400 . . . . . . . . . . . . . . . . 142
11.4 A request packet to access V1 in EM6400 . . . . . . . . . . . . . . . 143
11.5 A response packet to access V1 in EM6400 . . . . . . . . . . . . . . . 144
11.6 Memory storage of a four-byte integer in little-endian and big-endian 145
11.7 Xcos parameters to read energy meter values . . . . . . . . . . . . . 157

A.1 Approximate cost of the components . . . . . . . . . . . . . . . . . . 159


List of Arduino Code

3.1 First 10 lines of the FLOSS firmware . . . . . . . . . . . . . . . . . 27

4.1 Turning on the blue LED . . . . . . . . . . . . . . . . . . . . . . . 50


4.2 Turning on the blue LED and turning it off after two seconds . . . 50
4.3 Turning on blue and red LEDs for 5 seconds and then turning them
off one by one . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.4 Blinking the green LED . . . . . . . . . . . . . . . . . . . . . . . . 51

5.1 Read the status of the pushbutton and display it on the Serial Monitor 63
5.2 Turning the LED on or off depending on the pushbutton . . . . . . 63

6.1 Read and display the LDR values . . . . . . . . . . . . . . . . . . . 76


6.2 Turning the red LED on and off . . . . . . . . . . . . . . . . . . . . 76

7.1 Turning on LEDs depending on the potentiometer threshold . . . . 86

8.1 Read and display the thermistor values . . . . . . . . . . . . . . . . 96


8.2 Turning the buzzer on using thermistor values . . . . . . . . . . . . 97

9.1 Rotating the servomotor to a specified degree . . . . . . . . . . . . 112


9.2 Rotating the servomotor to a specified degree and reversing . . . . 112
9.3 Rotating the servomotor in increments . . . . . . . . . . . . . . . . 113
9.4 Rotating the servomotor through the potentiometer . . . . . . . . . 113

10.1 Rotating the DC motor . . . . . . . . . . . . . . . . . . . . . . . . . 128


10.2 Rotating the DC motor in both directions . . . . . . . . . . . . . . 128
10.3 Rotating the DC motor in both directions in a loop . . . . . . . . . 129

11.1 First 10 lines of the firmware for Modbus Energy Meter experiment 149

xv
xvi List of Arduino Code
List of Scilab Code

3.1 A Scilab code to check whether the firmware is properly installed or


not . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

4.1 Turning on the blue LED . . . . . . . . . . . . . . . . . . . . . . . 53


4.2 Turning on the blue LED and turning it off after two seconds . . . 54
4.3 Turning on blue and red LEDs for 5 seconds and then turning them
off one by one . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
4.4 Blinking the green LED . . . . . . . . . . . . . . . . . . . . . . . . 54

5.1 Read the status of the pushbutton and display it on the GUI . . . 65
5.2 Turning the LED on or off depending on the pushbutton . . . . . . 66

6.1 Read and display the LDR values . . . . . . . . . . . . . . . . . . . 78


6.2 Turning the red LED on and off . . . . . . . . . . . . . . . . . . . . 78

7.1 Turning on LEDs depending on the potentiometer threshold . . . . 88

8.1 Read and display the thermistor values . . . . . . . . . . . . . . . . 100


8.2 Turning the buzzer on using thermistor values . . . . . . . . . . . . 100

9.1 Rotating the servomotor to a specified degree . . . . . . . . . . . . 116


9.2 Rotating the servomotor to a specified degree and reversing . . . . 116
9.3 Rotating the servomotor in steps of 20◦ . . . . . . . . . . . . . . . . 116
9.4 Rotating the servomotor to a degree specified by the potentiometer 116

10.1 Rotating the DC motor . . . . . . . . . . . . . . . . . . . . . . . . . 132


10.2 Rotating the DC motor in both directions . . . . . . . . . . . . . . 132
10.3 Rotating the DC motor in both directions in a loop . . . . . . . . . 133

11.1 First 10 lines of the function for scifunc block . . . . . . . . . . . . 151


11.2 First 10 lines of the code for single phase current output . . . . . . 151

xvii
xviii List of Scilab Code

11.3 First 10 lines of the code for single phase voltage output . . . . . . 152
11.4 First 10 lines of the code for single phase active power output . . . 152
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

xix
xx 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,
1
Simulink® is a registered trademark of Mathworks, Inc.
2 1. 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 .

2
This 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,
4 2. 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.
6 2. 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.
8 2. 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 C like 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.
14 2. Hardware Environment

Figure 2.10: Pictorial representation of the schematic of the shield

To carry out all the experiments using a breadboard, as explained in the subsequent
chapters, one needs the components listed in Table 2.4.
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. Scilab 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 meant t o b e u s e d w i t h t h e FLOSS−A r d u i n o
2 t o o l b o x , h o w e v e r , i t c a n b e u s e d f r o m t h e IDE e n v i r o n m e n t
3 ( o r an y o t h e r s e r i a l t e r m i n a l ) by t y p i n g commands l i k e :
4
5 C o n v e r s i o n a s c i i −> number
6 48 − > ’0 ’ . . . 57 − > ’9 ’ 5 8 − > ’ : ’ 5 9 − > ’ ; ’ 60 − > ’ < ’ 61 − > ’= ’ 62 − > ’ > ’ 63 − > ’? ’
64 − > ’@ ’
7 65 − > ’A ’ . . . 90 − > ’Z ’ 9 1 − > ’ [ ’ 92 − > ’\ ’ 9 3 − > ’ ] ’ 94 − > ’^ ’ 95 − > ’_ ’ 96 − > ’ ‘ ’
8 97 − > ’ a ’ . . . 122 − > ’ z ’
9
10 Dan0 o r Dan1 : a t t a c h digital pin n ( a s c i i from 2 to b ) to input (0)
or output (1)

3.2 Scilab
Scilab is a free and open-source computing software for science and engineering ap-
plications [12]. It is released under GPL compatible CeCILL license. It uses the
28 3. Communication between Software and Arduino

state-of-the-art linear algebra package LAPACK, just as in Matlab. Scilab has hun-
dreds of inbuilt functions which cater to a variety of areas such as signal processing,
control system design, statistics, optimization, and many more. It has 2D and 3D
visualisation capabilities for generating excellent plots. It provides Matlab binary
files reading and writing capabilities and also a Matlab to Scilab conversion tool.
Scilab can also interact with other major programming languages such as Fortran,
C, C++, Python, Java, and TCL/TK [13]. It has a graphical editor called Xcos,
which is similar to Simulink of Matlab.
In the upcoming sections, we have provided the steps to install Scilab on Windows
and Linux. After installing Scilab, the readers are advised to watch the tutorials on
Scilab provided on https://spoken-tutorial.org/. Ideally, one should go
through all the tutorials labeled as Basic. However, we strongly recommend the
readers should watch the sixth and thirteenth tutorials, i.e., Getting Started
and Xcos Introduction.

3.2.1 Downloading and installing on Windows


This book uses Scilab 5.5.2 for demonstrating the experiments, both on Windows
and Linux. Starting from download, we shall go through the steps to set up Scilab
5.5.2 on Windows OS:
1. Visit the URL https://www.scilab.org/. At the top of the page, locate
the Download tab and click on it. It will take you to various software versions
available for Scilab. On the left side of this page, find Scilab 5.5.2 and click
on it. Now, download the executable file for Scilab 5.5.2 compatible with your
machine. We will download Scilab 5.5.2 - Windows 64 bits provided under
Windows Vista, 7, 8, 10.
2. Locate the executable (.exe) file and double-click on it to begin the installation.
All the default parameters of installation are acceptable. It may be noted that
Scilab requires internet connectivity during installation on Windows. There is
an option at the beginning of the installation to continue offline, but it is not
recommended.
Once the installation is complete, Scilab can be launched either from the Start
menu or by double-clicking on the Scilab icon created on the Desktop.

3.2.2 Downloading and installing on GNU/Linux Ubuntu


Package managers of Linux do not have the latest versions of Scilab. So, we will in-
stall Scilab by downloading the executable file from https://www.scilab.org/.
Starting from download, we shall go through the steps to set up Scilab 5.5.2 on Linux:
3.2. Scilab 29

Figure 3.6: Linux terminal to launch Scilab

1. Visit the URL https://www.scilab.org/. At the top of the page, locate


the Download tab and click on it. It will take you to various software versions
available for Scilab. On the left side of this page, find Scilab 5.5.2 and click
on it. Now, download the executable file for Scilab 5.5.2 compatible with
your machine. We will download Scilab 5.5.2 - Linux 64 bits provided under
GNU/Linux.

2. Locate the executable (tar.gz) file and extract it. It is a portable version and
needs no installation. Scilab can be launched and used right away.

To launch Scilab, open a terminal by pressing the Alt+Ctrl+T keys together.


Change the directory where Scilab is extracted. Browse till the /bin directory.
Type the command ls to see a few Scilab files. Then execute the command sudo
./scilab. Note that Scilab needs to be launched with root permissions to be able
to communicate with Arduino Uno. This process is illustrated in Fig. 3.6.

3.2.3 Scilab-Arduino toolbox


Scilab, by default, does not have the capability to connect to Arduino. All such add-
on functionalities are added to Scilab using toolboxes. Just like we have different
installation binaries of Scilab for Windows and Linux, we have different toolboxes
types for Windows and Linux. The Scilab Arduino toolbox can be found inside
the Origin/tools/scilab/windows or Origin/tools/scilab/linux di-
rectory, see Footnote 2 on page 2. Use the one depending upon which operating
system you are using. The Scilab 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.
Let us now see how to load the Scilab-Arduino toolbox.

1. First launch Scilab. On a Windows system, one may start/launch Scilab either
through the Start menu or by double-clicking on the shortcut icon created on
30 3. Communication between Software and Arduino

Figure 3.7: Browsing toolbox directory

the Desktop. On a Linux system, one has to start Scilab through a terminal
with root permissions, as explained in section 3.2.2.

2. After launching Scilab, first we have to change the working directory. Below the
menu bar, locate the tab called File Browser. Just below File Browser,
locate a folder-shaped icon. This icon is used to Select a directory.
Click on this icon.

3. Then, one has to browse to the toolbox folder Origin/tools/scilab/windows


or Origin/tools/scilab/linux, as the case may be, and click on, Open,
as shown in Fig. 3.7.

4. After the previous step, the Scilab working directory becomes the toolbox
folder. See the file browser panel on the left-hand side of the Scilab con-
sole, see Fig. 3.8. It will list out the contents of your current working directory.
For a check, look for the file builder.sce. If you see this file, then you are
in the right directory.

5. Next, type the following command on the Scilab console: exec builder.sce
3.2. Scilab 31

Figure 3.8: Output of builder.sce

- this will build the toolbox and create a file loader.sce. This step has to be
executed only the first time. The output of this step is illustrated in Fig. 3.8.

6. Next, type the command, exec loader.sce - this will load the toolbox.
This means all the new functions corresponding to the toolbox are loaded in
the workspace. It will also make available new Xcos blocks, if any. The output
of this command is as shown in Fig. 3.9. If you clear the workspace for any
reason, you will have to execute this command once again3 .

The toolbox is now loaded and available for use.

3.2.4 Identifying Arduino communication port number


Connect Arduino Uno board to your computer. On a Windows system, doing so
for the first time will initiate the Windows device identification routine. It may
3
Be careful not to execute the clear command. This will clear the loaded toolbox and you will
have to execute the loader.sce file again.
32 3. Communication between Software and Arduino

Figure 3.9: Output of loader.sce

take a while before it finishes assigning a COM port number to the Arduino Uno
board. If Arduino IDE is installed using the procedure outlined in Sec. 3.1, required
USB drivers for Arduino get installed automatically. Hence if you have installed the
Arduino IDE, it should not ask for drivers after you connect it. As usually Linux
systems come with required drivers, the device is automatically detected by the OS
on connection.
Now let us see how to identify the COM port number. For a Windows system,
open the Device Manager. To do so, right-click on “My Computer” and choose
Properties. The Properties window that will open will have Device Manager in the
list on the left-hand side. In the Device Manager window, look for “Ports (COM and
LPT)”. Double click on it. It will show you the COM number for Arduino Uno.
The result of the above exercise is shown in Fig. 3.10. In this case, the system
has detected Arduino with port number 3, which appears as COM3. In this book,
we have taken the port for communication as 2 and written code consistent with
this assumption. As a result, we will now change it to COM24 . To change the port
number, double click on the port number. Its properties window will appear. Click
on the “Port Settings” tab and then click on “Advanced” button as shown in Fig. 3.11.
Click on the drop-down menu for COM port numbers. Choose the port number
4
It is possible to leave it at whatever port number one gets. It is also possible to choose any
number between 2 and 99. In this case, the port number should be changed accordingly in the
code. We will point this out throughout the book.
3.2. Scilab 33

Figure 3.10: Device Manager in windows

COM2. On clicking on “OK”, Windows may warn you that the port number is
already in use. But given that you do not have any other USB device connected
you may force change it. Click on “OK” to close all of the device manager windows.
Now, we are set to go ahead with port number 2. The stress on using port number
2 is just to be consistent throughout the book. It is mainly for a beginner.
Now, let us see how to identify the port number on a Linux system. Open a
terminal by pressing Alt+Ctrl+T keys together. Then type the following command
and press enter, ls /dev/ttyACM* - the output of this command is shown in
Fig. 3.12. It has detected the Arduino with the port number “ttyACM0”. The last
character in this string, namely 0, is the port number. You may get 0 or a number
such as 1 or 2 in your case, for the port number.

3.2.5 Testing Scilab-Arduino toolbox


Now let us test the functioning of the toolbox.
34 3. Communication between Software and Arduino

Figure 3.11: COM port properties window

Figure 3.12: Port number on Linux terminal

1. Install Arduino IDE, as explained in Sec. 3.1 and launch it.

2. Read into the Arduino IDE, the firmware Arduino Code 3.1.

3. Using the Upload option of the Arduino IDE, load this firmware on to the
Arduino Uno board.

4. Inside the Origin/tools/scilab directory, locate a file test_firmware.sce.


This file will be used to test whether the firmware is properly installed. This
3.2. Scilab 35

is an important step, as the connection between the computer and Arduino


breaks down sometimes. The Scilab toolbox is unable to identify this difficulty
- it has to be externally done. If this difficulty is not identified and rectified,
one will waste a lot of time and effort trying to debug the error. This test has
to be done in case of difficulties.

5. In the Scilab console, type editor and press the enter key. This will launch
the editor. Click on “File” menu and choose “Open”. Browse to the directory
Origin/tools/scilab and choose the file test_firmware.sce. It will
open Scilab Code 3.1.

6. If you are using a Windows system and have set your port number as COM2,
you need not make any changes to the file. Linux users, however, will mostly
identify the port number as “ttyACM0”. Hence, they need to change the fol-
lowing line number
1 h = open_serial (1 ,2 ,115200) ;

to
h = open_serial (1 ,0 ,115200) ;

7. To execute this code, on the menu bar, click on the Execute, option. Then
choose File with no echo. The output will appear on the Console as
shown in Fig. 3.13. As shown in the figure, we see the response of this code as
“ans = ” and “ok” three times. The code basically gives some input to Arduino
three times and the program inside it returns “ok” three times. This code thus
confirms the working of the Scilab-Arduino toolbox. The code also confirms
that the firmware inside the Arduino is correct. It is alright if one or two of
the attempts out of three give a blank response. But all the three responses
certainly should not be blank5 .
Now let us take a look at the various functions facilitated by the toolbox. The
functions provided in the toolbox are as shown in Fig. 3.14. They are basically
categorized into four categories: configuration, digital, analog and motors. These
functions will be explained in detail in the subsequent chapters as and when they
are used.

3.2.6 Firmware
We have provided a Scilab code to check whether the firmware has been properly
installed. That code is listed below.
5
If this step is unsuccessful, one should check the connections and re-install the firmware
36 3. Communication between Software and Arduino

Figure 3.13: Scilab test code output

Figure 3.14: Arduino toolbox functions used in this book

Scilab Code 3.1 A Scilab code to check whether the firmware is properly installed
or not. Available at Origin/tools/scilab/test_firmware.sce, see Foot-
note 2 on page 2. Execute this code by following the steps given in section 3.2.5.
3.3. Xcos 37

1 mode ( 0 )
2 h = open_serial (1 ,2 ,115200) ;
3 for i = 1 : 3
4 w r i t e _ s e r i a l ( 1 , "v" , 1 ) ;
5 read_serial (1 ,2)
6 end
7 close_serial (1) ;

3.3 Xcos
Xcos is a graphical editor for Scilab [14]. Most of the mathematical manipulations
that can be done using Scilab scripts, can be done using Xcos also. The major
advantage of Xcos is the intuitive interface and easy connectivity across blocks.
Xcos even supports if else, for, and while looping which forms an integral
part of any programming language. It is possible to code the entire algorithm using
Xcos blocks alone. It is also possible to read from and write to the Scilab workspace
through Xcos.

3.3.1 Downloading, installing and testing


Xcos comes pre-installed with Scilab. Hence a separate installation of Xcos is not
required. Let us explore the functionalities Xcos has to offer. Xcos basically provides
a graphical interface to Scilab.
Xcos can be launched from Scilab by clicking on the Xcos icon available on the
Scilab menu bar. It can also be launched by simply typing the command xcos in
the Scilab console. When Xcos is launched, it will open a palette browser. We have
shown this in Fig. 3.15, where we have selected a sine block. At the time of launch,
Xcos will also open an empty canvas, called an untitled Xcos window.
Palette browser shows all of the available blocks that can be used. It has been
nicely categorized as per the functionality. For example, blocks that generate sig-
nals/values without any input, fall under the category Sources. Similarly, blocks
that take signals/values without giving any output are categorized as Sinks. This
makes finding a particular block very easy, specially when one does not know the
name of a block.
The untitled window is the one where one creates the Xcos code/diagram. The
relevant blocks have to be dragged and dropped from the palette browser to the
untitled window. The blocks are then interconnected and configured as per the
simulation, which we will demonstrate next.
38 3. Communication between Software and Arduino

Figure 3.15: Sine generator in palette browser

3.3.2 Use case


Let us build a simple Xcos simulation to plot a sine wave. This simulation requires
a sine wave source. It can be found in the Sources category as shown in Fig. 3.15.
Drag and drop this block in the untitled Xcos window.
Next, we need a block to plot the sine wave. A plotting block can be found in
the Sinks category as shown in Fig. 3.16. The name of this block is CSCOPE.
Drag and drop this block in the untitled Xcos window. On the left-hand side, this
block has an input port for data. It is black in colour, which may not be obvious
in a black and white printout. The output from the sine block has to be connected
to this port. At its top side, the CSCOPE block has another input port, called an
3.3. Xcos 39

Figure 3.16: CSCOPE block in xcos

Figure 3.17: CLOCK_c block in xcos

event port. This is red in colour. This port is used to synchronize it with event
generating devices.
As the CSCOPE block has an input event port, we need a source that generates
events. Hence, the next block that we need is an event generator block and it can
be found in the Sources category. This is illustrated in figure 3.17. The name of
this block is CLOCK_c. Drag and drop this block in the untitled Xcos window.
The next step is to interconnect the blocks together. A black color port can only
be connected to another black color port. A black color port cannot be connected to
a red color port and vice versa. That is, a data port cannot be connected to an event
port. Linking two blocks is a bit crucial and may need a few attempts before one
gets comfortable. To link two blocks, first click and hold the left mouse button over
the output port of the source block. Without releasing the mouse button, touch the
mouse pointer to the input port of the sink block. If a connection is possible there,
the port will turn “green”. At this point, release the mouse button and the blocks
should get connected. Follow this procedure and complete the connection as shown
40 3. Communication between Software and Arduino

Figure 3.18: Sine generator in Xcos

Figure 3.19: Sine generator Xcos output

in Fig. 3.18. Save this file with the name sine-generator.


Let us simulate this Xcos code. On the menu bar, click on the Simulation
menu and choose Start. You will get a graphic window with a running sine wave
as shown in Fig. 3.19.
This is because we are running the simulation using the default configuration. We
would like a stationary plot. If the simulation is still running, go to the Simulation
menu and choose Stop. Double click on the CSCOPE block. Its properties window
will appear as shown in 3.20. Note the value of the Refresh period. It is by
default 30. Click on Ok.
3.3. Xcos 41

Figure 3.20: CSCOPE configuration window

Next, on the menu bar, click on the Simulation menu and choose Setup. The
Set Parameters window will open. The first parameter is Final integration
time. It decides for how long the simulation will run. Change it to be equal to the
Refresh period of the CSCOPE block. That is, change it to 30 as shown in
Fig. 3.21. Now start the simulation and you will get a static plot. Other para-
menters of blocks can also be changed. For example, one may want to change the
input amplitude/frequency or change the plot scales, etc. All these are left to the
reader to explore.

Although we have demonstrated a very basic level of Xcos simulation, this idea
can be used for complex processes as well. Using Xcos, it is possible to have user-
defined blocks. The user can code the working of the block as a function in Scilab
script and then call it from Xcos. It is also possible to create subsystems. One
can even read from and write to C binaries. Xcos comes with several pre-defined
libraries and hence, it is possible to carry out other kinds of simulation, such as
electrical circuit simulation and basic thermo-hydraulic simulation, for example. A
detailed explanation and demonstration are beyond the scope of this book.
42 3. Communication between Software and Arduino

Figure 3.21: Simulation setup window

Figure 3.22: Palette browser showing Arduino blocks

3.3.3 Xcos-Arduino
The Scilab Arduino toolbox not only provides functions to be used in Scilab scripts
but also provides new Arduino-specific blocks. As shown in Fig. 3.22 new Arduino
blocks are now available for use. Similar to the categorization of the functions,
the Xcos blocks are also categorized as configuration, digital, analog and motors.
Again, it is possible to conduct the experiments only using Xcos. Xcos codes for
every experiment are provided throughout the book. The Arduino blocks can be
easily connected to Xcos native blocks. A detailed block help for every block can be
sought by right-clicking on the block and choosing “Block help”. This is illustrated
in Fig. 3.23.
3.3. Xcos 43

Figure 3.23: Xcos block help


44 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


46 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 47

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
48 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:
1 d 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,
1 pinMode ( 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:
1 delay (2000) ;

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,
1 d 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 49

// 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.
50 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.
1 void s e t u p ( ) {
2 pinMode ( 9 , OUTPUT) ;
3 S e r i a l . begin (115200) ;
4 d i g i t a l W r i t e ( 9 , HIGH) ;
5 }
6 void l o o p ( ) {
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.
1 void s e t u p ( ) {
2 pinMode ( 9 , OUTPUT) ;
4.3. Lighting the LED from the Arduino IDE 51

3 S e r i a l . begin (115200) ;
4 d i g i t a l W r i t e ( 9 , HIGH) ;
5 delay (2000) ;
6 d i g i t a l W r i t e ( 9 , LOW) ;
7 }
8 void l o o p ( ) {
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.
1 void s e t u p ( ) {
2 pinMode ( 9 , OUTPUT) ;
3 pinMode ( 1 1 , OUTPUT) ;
4 S e r i a l . begin (115200) ;
5 d i g i t a l W r i t e ( 9 , HIGH) ;
6 d i g i t a l W r i t e ( 1 1 , HIGH) ;
7 delay (5000) ;
8 d i g i t a l W r i t e ( 9 , LOW) ;
9 delay (3000) ;
10 d i g i t a l W r i t e ( 1 1 , LOW) ;
11 }
12 void l o o p ( ) {
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.
1 int i = 0 ;
2 void s e t u p ( ) {
3 pinMode ( 1 0 , OUTPUT) ;
4 S e r i a l . begin (115200) ;
5 f o r ( i = 0 ; i < 5 ; i ++)
6 {
7 d i g i t a l W r i t e ( 1 0 , HIGH) ; / / t u r n t h e LED on ( HIGH i s the voltage
level )
8 delay (1000) ; // w a i t f o r a s e c o n d
9 d i g i t a l W r i t e ( 1 0 , LOW) ; / / t u r n t h e LED o f f by m a k i n g t h e voltage
LOW
10 delay (1000) ; // w a i t f o r a second
11 }
12 }
13 void l o o p ( ) {
14 }
52 4. Interfacing a Light Emitting Diode

4.4 Lighting the LED from Scilab


4.4.1 Lighting the LED
In this section, we discuss how to carry out the experiments of the previous section
from Scilab. 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 Scilab Code 4.1. It begins with a command of the form
ok = o p e n _ s e r i a l ( 1 , PORT NUMBER, BAUD RATE)

We have used 2 for PORT NUMBER and 115200 for BAUD RATE. As a result,
this command becomes
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; / / At p o r t 2 w i t h b a u d r a t e o f
115200

This command is used to open the serial port. When the port is opened
successfully, it returns a value of 0, which gets stored in the variable ok.
Sometimes, the serial port does not open, as mentioned in the above command.
This is typically due to not closing the serial port properly in a previous exper-
iment. If this condition is not trapped, the program will wait forever, without
any information about this difficulty. One way to address this difficulty is to
terminate the program if the serial port does not open. This is achieved using
the error message of the following form:
i f ok ~= 0 , e r r o r ( E r r o r Message i n Quotes ) ;

It checks if ok = 0. If not, it flashes an error message and terminates. This


line gets implemented in the following way in Scilab Code 4.1.
1 i f ok ~= 0 , e r r o r ( ’ Check t h e s e r i a l p o r t and t r y a g a i n ’ ) ; end

We turn the LED on in the next line. This is achieved using a command of
the form
cmd_digital_out ( 1 , PIN NUMBER, VALUE)
4.4. Lighting the LED from Scilab 53

As we want to turn on the blue light in the shield, as discussed in Sec. 4.3.1,
we choose PIN NUMBER as 9. We can put any positive integer in the place of
VALUE. We arrive at the following command:
1 cmd_digital_out ( 1 , 9 , 1 ) // Th i s will turn the b l u e LED

The last line in the code closes the serial port. As mentioned above, it is
extremely important to close the serial port properly. If not closed properly,
there could be difficulties in running subsequent programs.

2. Scilab Code 4.2 does the same thing as what Arduino Code 4.2 does. It does
two more things than what Scilab Code 4.1 does: It makes the blue LED light
up for two seconds. This is achieved by the command
1 sleep (2000) // let the b l u e LED b e on f o r two s e c o n d s

The second thing this code does is to turn the blue LED off. This is achieved
by the command
1 cmd_digital_out ( 1 , 9 , 0 ) / / t u r n o f f b l u e LED

It is easy to see that this code puts a 0 on pin 9.

3. Scilab 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. Scilab 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.

4.4.2 Scilab Code


Scilab Code 4.1 Turning on the blue LED. Available at Origin/user-code/l
ed/scilab/led-blue.sce, see Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; / / At p o r t 2 w i t h b a u d r a t e o f 1 1 5 2 0 0
2 i f ok ~= 0 , e r r o r ( ’ Check t h e s e r i a l p o r t and t r y a g a i n ’ ) ; end
3 cmd_digital_out ( 1 , 9 , 1 ) / / T h i s w i l l t u r n t h e b l u e LED
4 close_serial (1) ; / / To c l o s e t h e c o n n e c t i o n s a f e l y
54 4. Interfacing a Light Emitting Diode

Scilab Code 4.2 Turning on the blue LED and turning it off after two seconds.
Available at Origin/user-code/led/scilab/led-blue-delay.sce, see
Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ;
2 i f ok ~= 0 , e r r o r ( ’ Check t h e s e r i a l p o r t and t r y a g a i n ’ ) ; end
3 cmd_digital_out ( 1 , 9 , 1 ) / / t u r n b l u e LED on
4 sleep (2000) / / l e t t h e b l u e LED b e on f o r two s e c o n d s
5 cmd_digital_out ( 1 , 9 , 0 ) / / t u r n o f f b l u e LED
6 close_serial (1) ; // c l o s e t h e c o n n e c t i o n s a f e l y

Scilab 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/scilab/led-blu
e-red.sce, see Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; / / At p o r t 2 w i t h b a u d r a t e o f 1 1 5 2 0 0
2 i f ok ~= 0 e r r o r ( ’ Check t h e s e r i a l p o r t and t r y a g a i n ’ ) ; end
3 cmd_digital_out ( 1 , 9 , 1 ) ; / / T h i s t u r n s on t h e b l u e Led
4 cmd_digital_out ( 1 , 1 1 , 1 ) ; / / T h i s t u r n s on t h e r e d Led
5 sleep (5000) ; // Delay f o r 5 s e c o n d s
6 cmd_digital_out ( 1 , 9 , 0 ) ; / / T h i s t u r n s o f f t h e b l u e Led
7 sleep (3000) ; // Delay f o r 3 s e c o n d s
8 cmd_digital_out ( 1 , 1 1 , 0 ) ; / / T h i s t u r n s o f f t h e r e d Led
9 close_serial (1) ; / / To c l o s e t h e c o n n e c t i o n s a f e l y

Scilab Code 4.4 Blinking the green LED. Available at Origin/user-code/le


d/scilab/led-green-blink.sce, see Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; / / At p o r t 2 w i t h b a u d r a t e o f 1 1 5 2 0 0
2 i f ok ~= 0 e r r o r ( ’ Check t h e s e r i a l p o r t and t r y a g a i n ’ ) ; end
3 for i = 1 : 5 // Running f o r loop , 5 t i m e s
4 cmd_digital_out ( 1 , 1 0 , 1 ) ; / / T h i s t u r n s on t h e g r e e n Led
5 sleep (1000) ; // Delay f o r 1 s e c o n d
6 cmd_digital_out ( 1 , 1 0 , 0 ) ; / / T h i s t u r n s o f f t h e g r e e n Led
7 sleep (1000) ; // Delay f o r 1 s e c o n d
8 end
9 close_serial (1) ; / / To c l o s e t h e c o n n e c t i o n s a f e l y

4.5 Lighting the LED from Scilab Xcos


In this section, we will see how to light the LEDs from Scilab Xcos. We will carry
out the same four experiments as in the previous sections. For each, we will give the
location of the zcos file and the parameters to set. The reader should go through
the instructions given in Sec. 3.3 before getting started.
4.5. Lighting the LED from Scilab Xcos 55

Figure 4.6: Turning the blue LED on through Xcos. This is what one sees when Or
igin/user-code/led/scilab/led-blue.zcos, see Footnote 2 on page 2 is
invoked.

Table 4.1: Parameters to light the blue LED in Xcos

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
DIGITAL_WRITE_SB Digital pin 9
Arduino card number 1

1. First we will see how to turn on the blue LED. When the file required for this
experiment is invoked, one gets the GUI as in Fig. 4.6. In the caption of this
figure, one can see where to locate the file.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 4.1. All other
parameters are to be left unchanged.

2. In the second experiment, we will show how to turn on the blue LED on for
two seconds and then to turn it off. When the file required for this experiment
is invoked, one gets the GUI as in Fig. 4.7. In the caption of this figure, one
can see where to locate the file.
The values for each block required in this program are tabulated in Table 4.2.
56 4. Interfacing a Light Emitting Diode

Figure 4.7: Turning the blue LED on through Xcos for two seconds. This is what
one sees when Origin/user-code/led/scilab/led-blue-delay.zcos, see
Footnote 2 on page 2 is invoked.

Table 4.2: Parameters to light the blue LED in Xcos for two seconds

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
DIGITAL_WRITE_SB Digital pin 9
Arduino card number 1
STEP_FUNCTION Step time 2
Initial value 1
Final value 0

All other parameters are to be left unchanged.

3. In the third experiment, we will show how to turn the blue LED and the red
LED on for five seconds, turn off the blue LED and three seconds later, turn
off the red LED also. When the file required for this experiment is invoked,
one gets the GUI as in Fig. 4.8. In the caption of this figure, one can see where
to locate the file.
The values for each block required in this program are tabulated in Table 4.3.
All other parameters are to be left unchanged.

4. We will conclude this section with an experiment to blink the green LED on
4.5. Lighting the LED from Scilab Xcos 57

Figure 4.8: Turning the blue and red LEDs on through Xcos and turning them off
one by one. This is what one sees when Origin/user-code/led/scilab/led
-blue-red.zcos, see Footnote 2 on page 2 is invoked.

Table 4.3: Parameters to turn the blue and red LEDs on and then turn them off one
by one

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
DIGITAL_WRITE_SB 1 Digital pin 9
Arduino card number 1
STEP_FUNCTION 1 Step time 5
Initial value 1
Final value 0
DIGITAL_WRITE_SB 2 Digital pin 11
Arduino card number 1
STEP_FUNCTION 2 Step time 8
Initial value 1
Final value 0

and off. When the file required for this experiment is invoked, one gets the
GUI as in Fig. 4.9. In the caption of this figure, one can see where to locate
the file.
58 4. Interfacing a Light Emitting Diode

Figure 4.9: Blinking the green LED every second through Xcos. This is what one
sees when Origin/user-code/led/scilab/led-green-blink.zcos, see
Footnote 2 on page 2 is invoked.

Table 4.4: Parameters to make the green LED blink every second

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
DIGITAL_WRITE_SB Digital pin 10
Arduino card number 1
PULSE_SC Pulse width(% of period) 50
Period(secs) 2
Phase delay(secs) 0.1
Amplitude 1

The values for each block required in this program are tabulated in Table 4.4.
All other parameters are to be left unchanged.

Exercise 4.3 Carry out the following exercise:

1. Change the blink pattern for an array of LEDs.


2. Change the delays.
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.
60 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 61

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
62 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:
1 s e n s o r V a l u e = d i g i t a l R e a d ( s e n s o r P i n ) ; / / r e a d push −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,
1 S e r i a l . p r i n t l n ( sensorValue ) ; // p r i n t i t a t t h e S e r i a l
Monitor

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 63

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,
1 pinMode ( s e n s o r P i 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.
1 const i n t s e n s o r P i n = 1 2 ; / / D e c l a r e t h e push −b u t t o n
2 int sensorValue = 0 ;
3 void s e t u p ( ) {
4 S e r i a l . begin (115200) ;
5 pinMode ( s e n s o r P i n , INPUT) ; / / d e c l a r e t h e s e n s o r P i n a s an INPUT
6 f o r ( i n t i = 0 ; i < 5 0 ; i ++){
7 s e n s o r V a l u e = d i g i t a l R e a d ( s e n s o r P i n ) ; / / r e a d push −b u t t o n v a l u e
8 S e r i a l . p r i n t l n ( sensorValue ) ; // p r i n t i t a t t h e S e r i a l Monitor
9 delay (200) ;
10 }
11 }
12 void l o o p ( ) {
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.
1 const i n t s e n s o r P i n = 1 2 ;
2 const i n t l e d P i n = 9 ;
3 int sensorValue = 0 ;
4 int i ;
5 void s e t u p ( ) {
6 S e r i a l . begin (115200) ;
7 pinMode ( s e n s o r P i n , INPUT) ;
8 pinMode ( l e d P i n , OUTPUT) ;
9 f o r ( i = 0 ; i < 5 0 ; i ++) {
10 sensorValue = digitalRead ( sensorPin ) ;
11 S e r i a l . p r i n t l n ( sensorValue ) ; // p r i n t i t a t t h e S e r i a l Monitor
64 5. Interfacing a Pushbutton

12 i f ( s e n s o r V a l u e == 0 ) {
13 d i g i t a l W r i t e ( l e d P i n , LOW) ;
14 delay (200) ;
15 }
16 else {
17 d i g i t a l W r i t e ( l e d P i n , HIGH) ;
18 delay (200) ;
19 }
20 }
21 }
22 void l o o p ( ) {
23 }

5.4 Reading the pushbutton Status from Scilab


5.4.1 Reading the pushbutton Status
In this section, we discuss how to carry out the experiments of the previous section
from Scilab. 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 using a Graphi-
cal user interface (GUI) in Scilab. The code for this experiment is given in
Scilab Code 5.1. As explained earlier in Sec. 4.4.1, we begin with serial port
initialization. Then, we read the input coming from digital pin 12 using the
following command:
1 v a l = cmd_digital_in ( 1 , 1 2 ) ; / / Read t h e status of p i n 12

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 as a
GUI using the following command:
1 cmd_arduino_meter ( v a l ) ;

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 1000 iterations.
While running this experiment, the readers must press and release the push-
button and observe the values being printed on the GUI, as shown in Fig. 5.4.
5.4. Reading the pushbutton Status from Scilab 65

Figure 5.4: GUI in Scilab to show the status of the pushbutton

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 Scilab 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,
1 i f v a l == 0
2 cmd_digital_out ( 1 , 9 , 0 )
3 else
4 cmd_digital_out ( 1 , 9 , 1 )

perform the condition check and corresponding LED state control operation.
While running this experiment, the readers must press and release the push-
button. Accordingly, they can observe whether the LED glows when the push-
button is pressed.

5.4.2 Scilab Code


Scilab Code 5.1 Read the status of the pushbutton and display it on the GUI.
Available at Origin/user-code/push/scilab/push-button-status.sc
e, see Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; / / p o r t 2 , baud r a t e 1 1 5 2 0 0
2 i f ok ~= 0 then e r r o r ( ’ Unable t o open s e r i a l port , p l e a s e check ’ ) ; end
3 for i = 1:1000 / / Run f o r 1 0 0 0 i t e r a t i o n s
66 5. Interfacing a Pushbutton

4 v a l = cmd_digital_in ( 1 , 1 2 ) ; / / Read t h e status of p i n 12


5 cmd_arduino_meter ( v a l ) ;
6 end
7 close_serial (1) ; / / To c l o s e the connection safely

Scilab Code 5.2 Turning the LED on or off depending on the pushbutton. Avail-
able at Origin/user-code/push/scilab/led-push-button.sce, see Foot-
note 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; // p o r t 2 , b a u d r a t e 115200
2 i f ok ~= 0 then e r r o r ( ’ Unable t o open s e r i a l port , p l e a s e check ’ ) ; end
3 for i = 1:1000 / / Run f o r 1 0 0 0 i t e r a t i o n s
4 v a l = cmd_digital_in ( 1 , 1 2 )
5 cmd_arduino_meter ( v a l ) ;
6 i f v a l == 0
7 cmd_digital_out ( 1 , 9 , 0 )
8 else
9 cmd_digital_out ( 1 , 9 , 1 )
10 end
11 end
12 close_serial (1) ;

5.5 Accessing the pushbutton from Xcos


In this section, we will see how to access the pushbutton from Scilab Xcos. We will
carry out the same two experiments as in the previous sections. For each, will give
the location of the zcos file and the parameters to set. The reader should go through
the instructions given in Sec. 3.3 before getting started.

1. First we will read the push button value and print it. When the file required
for this experiment is invoked, one gets the GUI as in Fig. 5.5. In the caption
of this figure, one can see where to locate the file.
As discussed in earlier chapters, we start with the initialization of the serial
port. Next, using Digital Read block, we read the status of pushbutton
connected on digital pin 12. The read values are displayed. When a user
presses the pushbutton, change in the logic value from low to high can be
observed.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 5.1. All other
parameters are to be left unchanged.
5.5. Accessing the pushbutton from Xcos 67

Figure 5.5: Printing the push button status on the display block. This is what one
sees when Origin/user-code/push/scilab/push-button-status.zcos,
see Footnote 2 on page 2, is invoked.

Table 5.1: Parameters to print the push button status on the display block

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
DIGITAL_READ_SB Digital pin 12
Arduino card number 1
AFFICH_m Block inherits (1) or not (0) 1

2. In the second experiment, we take a step further and control the state of an
LED in accordance with the status of the pushbutton. The Xcos implemen-
tation for this experiment is shown in Fig. 5.6. Each time a user presses the
pushbutton, the LED on digital pin 9 of the shield is switched on. If the shield
is connected, the blue LED turns on. When the pushbutton is released, the
LED is switched off. Here, we note that the digital logic level of the pin of
the Arduino Uno board connected to pushbutton changes only for the time the
pushbutton is being pressed.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
68 5. Interfacing a Pushbutton

Figure 5.6: Turning the LED on or off, depending on the pushbutton. This is what
one sees when Origin/user-code/push/scilab/led-push-button.zcos,
see Footnote 2 on page 2, is invoked.

Table 5.2: Xcos parameters to turn the LED on through the pushbutton

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
DIGITAL_READ_SB Digital pin 12
Arduino card number 1
DIGITAL_WRITE_SB Digital pin 9
Card number 1

double click. The values for each block is tabulated in Table 5.2. All other
parameters are to be left unchanged.

Exercise 5.1 Let us carry out the following exercise:


1. In the above experiment, we controlled only one LED upon pushbutton press.
Next, control multiple devices upon the pushbutton press. For example,
upon press, turn on an LED and a motor and turn them off upon release.
2. Control several devices depending on the number of pushbutton press in a
definite time span. For example, if the pushbutton is pressed once in time
’t’,say, turn on the LED. If it is pressed twice in time ’t’, turn on the motor.
Here, you may want to consider the timing between two consecutive press.
5.5. Accessing the pushbutton from Xcos 69
70 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.
72 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 73

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
74 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,
1 v a l = analogRead (A5) ; // v a l u e o f LDR
6.3. Interfacing the LDR through the Arduino IDE 75

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,
1 S e r i a l . println ( val ) ; // for display

The delay in the code


1 delay (500) ;

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.
76 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.
1 int val ; / / f o r LDR
2 int i = 1 ;
3 void s e t u p ( ) {
4 S e r i a l . begin (115200) ;
5 f o r ( i = 1 ; i <= 5 0 ; i ++){
6 v a l = analogRead (A5) ; / / v a l u e o f LDR
7 S 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
8 delay (500) ;
9 }
10 }
11 void l o o p ( ) {
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.
1 int val ;
2 int i = 1 ;
3 void s e t u p ( ) {
4 pinMode ( 1 1 , OUTPUT) ; / / LED P i n
5 S e r i a l . begin (115200) ;
6 f o r ( i = 1 ; i <= 5 0 ; i ++){
7 v a l = analogRead (A5) ; / / V a l u e o f LDR
8 S e r i a l . println ( val ) ;
9 i f ( val < 300) { // T h r e s h o l d
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 delay (500) ;
17 }
18 }
19 void l o o p ( ) {
20 }

6.4 Interfacing the LDR through Scilab


6.4.1 Interfacing the LDR
In this section, we discuss how to carry out the experiments of the previous section
from Scilab. We will list the same two experiments, in the same order. The shield
6.4. Interfacing the LDR through Scilab 77

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 and display it in Scilab
Console. The code for this experiment is given in Scilab Code 6.1. As explained
earlier in Sec. 4.4.1, we begin with serial port initialization. Then, we read the
input coming from analog pin 5 using the following command:
1 v a l = cmd_analog_in ( 1 , 5 ) ; // r e a d analog pin 5 ( ldr )

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 in the Scilab
Console by the following command:
1 disp ( val ) ;

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 the Scilab Console.

2. This experiment is an extension of the previous experiment. Here, depending


on the resistance of the LDR, we will turn the red LED on. The program for
this is available at Scilab 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.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.
78 6. Interfacing a Light Dependent Resistor

6.4.2 Scilab Code


Scilab Code 6.1 Read and display the LDR values. Available at Origin/user-
code/ldr/scilab/ldr-read.sce, see Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; / / P o r t 2 w i t h b a u d r a t e 1 1 5 2 0 0
2 i f ok ~= 0 then e r r o r ( ’ Unable t o open s e r i a l p o r t . P l e a s e check ’ ) ; end
3 for i = 1:50 / / Run f o r 5 0 i t e r a t i o n s
4 v a l = cmd_analog_in ( 1 , 5 ) ; // r e a d a n a l o g p i n 5 ( l d r )
5 disp ( val ) ;
6 sleep (500) // Delay o f 500 m i l l i s e c o n d s
7 end
8 c = close_serial (1) ; // c l o s e s e r i a l c o n n e c t i o n

Scilab Code 6.2 Turning the red LED on and off. Available at Origin/user-c
ode/ldr/scilab/ldr-led.sce, see Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; // p o r t 2 , b a u d r a t e 115200
2 i f ok ~= 0 then e r r o r ( ’ Unable t o open s e r i a l port , p l e a s e check ’ ) ; end
3 f o r i = 1 : 5 0 / / Run f o r 5 0 i t e r a t i o n s
4 v a l = cmd_analog_in ( 1 , 5 ) // r e a d a n a l o g p i n 5 ( l d r )
5 disp ( val ) ;
6 i f ( val < 300) // S e t t i n g T h r e s h o l d v a l u e o f 300
7 cmd_digital_out ( 1 , 1 1 , 1 ) / / Turn ON LED
8 else
9 cmd_digital_out ( 1 , 1 1 , 0 ) / / Turn OFF LED
10 end
11 sleep (500)
12 end
13 close_serial (1) ;

6.5 Interfacing the LDR through Xcos


Next, we shall perform the above mentioned experiments, to read LDR values,
through Xcos. We will carry out the same two experiments as in the previous sec-
tions. For each, will give the location of the zcos file and the parameters to set. The
reader should go through the instructions given in Sec. 3.3 before getting started.

1. First we will read the LDR values and display it. When the file required for
this experiment is invoked, one gets the GUI as in Fig. 6.5. In the caption of
this figure, one can see where to locate the file.
6.5. Interfacing the LDR through Xcos 79

Figure 6.5: Xcos diagram to read LDR values. This is what one sees when Ori
gin/user-code/ldr/scilab/ldr-read.zcos, see Footnote 2 on page 2, is
invoked.

Figure 6.6: Plot window in Xcos to read LDR values

As discussed in earlier chapters, we start with the initialization of the serial


port. Next, using Analog Read block, we read the values of LDR connected
on analog pin 5. Next, we use a scope to plot the values coming from this pin.
When this Xcos file is simulated, a plot is opened, as shown in Fig. 6.6.
80 6. Interfacing a Light Dependent Resistor

Table 6.1: Xcos parameters to read LDR

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
ANALOG_READ_SB Analog Pin 5
Arduino card number 1
CSCOPE Ymin 0
Ymax 1023
Refresh period 100
CLOCK_c Period 0.1
Initialisation Time 0

We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 6.1. All other
parameters are to be left unchanged.
During this experiment, we vary the light incident on LDR by using light
sources and obstacles such as torch light, paper, hand (or fingertips), etc. and
observe the LDR readings in the plot, as shown in Fig. 6.6. We observe that
with a constant light source, the LDR output saturates after some time.

2. In the second experiment, we take a step further and control the state of red
LED in accordance with the LDR values. When the file required for this
experiment is invoked, one gets the GUI as in Fig. 6.7. In the caption of this
figure, one can see where to locate the file.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 6.2. In the
CSCOPE_c block, the two values correspond to two graphs, one for digital
write and other for analog read values. All other parameters are to be left
unchanged. When this Xcos file is simulated, a plot is opened, as shown in
Fig. 6.8.
6.5. Interfacing the LDR through Xcos 81

Figure 6.7: Xcos diagram to read the value of the LDR, which is used to turn the
blue LED on or off. This is what one sees when Origin/user-code/ldr/scil
ab/ldr-led-xcos.zcos, see Footnote 2 on page 2, is invoked.

Figure 6.8: Plot window in Xcos to read LDR values and the state of LED
82 6. Interfacing a Light Dependent Resistor

Table 6.2: Xcos parameters to read LDR and regulate blue LED

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
ANALOG_READ_SB Analog pin 5
Arduino card number 1
CMSCOPE Ymin 00
Ymax 1 1023
Refresh period 100 100
CLOCK_c Period 0.1
Initialisation time 0
SWITCH2_m Datatype 1
threshold 300
pass first input if field 0
use zero crossing 1
DIGITAL_WRITE_SB Digital pin 9
Arduino card number 1
Chapter 7

Interfacing a Potentiometer

A potentiometer is a three-terminal variable resistor with two terminals connected


to the two ends of a resistor and one connected to a sliding or rotating contact,
termed as a wiper. The wiper can be moved to vary the resistance, and hence the
potential, between the wiper and each terminal of the resistor. Thus, a potentiometer
functions as a variable potential divider. It finds wide application in volume control,
calibration and tuning circuits, motion control, joysticks, etc.
In this chapter, we will perform an experiment to read the analog values from
a potentiometer mounted on the shield of Arduino Uno board. The analog values
read from the potentiometer will then be used to control the actuation of other
components.

7.1 Preliminaries
The shield provided with the kit has a 1K potentiometer mounted on it. The me-
chanical contact at the middle terminal is rotated to vary the resistance across the
middle terminal and the two ends of the potentiometer. With the fixed voltage
across the two terminals of the potentiometer, the position of the wiper determines
the potential across the middle terminal and either of the two end terminals. Nowa-
days, digital potentiometer integrated circuits, which vary resistance across two pins
on the basis of the set value, are also available.
The potentiometer used in the kit can be seen on the shield in Fig. 4.3 on page 46.
It is mounted on the shield. The two end terminals of the potentiometer are con-
nected to 5V supply and ground. The middle terminal is connected to analog pin 2
of the Arduino Uno board. The resistance between the middle terminal and either of
the two ends can be varied by rotating the middle terminal by hand. The connection
diagram for the potentiometer is shown in Fig. 7.1.
84 7. Interfacing a Potentiometer

(a) Pictorial representation of a potentiometer (b) Internal connection diagram for the poten-
tiometer on the shield

Figure 7.1: Potentiometer’s schematic on the shield

The reading of a potentiometer is an analog voltage varying from 0 to 5V. Like


LDR, we use the ADC functionality of the Arduino Uno board. Thus, we obtain
digital values between 0 and 1023. In the experiment explained in this chapter, we
shall also use an RGB LED mounted on the shield. An RGB LED is a tri-color LED
which can illuminate in Red, Green, and Blue colors. It has 4 leads of which one
lead is connected to ground and other three leads are connected to digital I/O pins
9, 10, and 11 of Arduino. In order to switch on a particular LED, we need to provide
HIGH (5V) voltage to the corresponding pin of the Arduino Uno board.

7.2 Connecting a potentiometer 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
7.3. Reading the potentiometer from the Arduino IDE 85

Figure 7.2: A potentiometer to control an LED with Arduino Uno using a breadboard

the fifth and sixth tutorials, i.e., First Arduino Program and Arduino with
Tricolor LED and Push button.
In case you have a potentiometer, and you want to connect it with Arduino Uno
on a breadboard, please refer to Fig. 7.2. The connections given in this figure can
be used to control an RGB LED depending upon the values from the potentiometer.
As shown in Fig. 7.2, the three legs of the potentiometer are connected to 5V, analog
pin 2, and GND on Arduino Uno. Depending upon how much the potentiometer’s
shaft is rotated, one can get a value on analog pin 2. On the other hand, there is an
RGB LED, and its four legs are connected to three different digital pins and GND
on Arduino Uno as discussed in Chapter 4.

7.3 Reading the potentiometer from the Arduino IDE


7.3.1 Reading the potentiometer
In this section, we shall learn how to read the potentiometer input through Arduino
IDE. Depending on the acquired potentiometer values, we will change the state of
the RGB LED. The shield has to be attached to the Arduino Uno board before doing
this experiment and the Arduino Uno needs to be connected to the computer with
86 7. Interfacing a Potentiometer

a USB cable, as shown in Fig. 2.4. The reader should go through the instructions
given in Sec. 3.1 before getting started.
The Arduino code for this experiment is given in Arduino Code 7.1. In this code,
lines 1 through 4 are used to assign relevant PINs to the potentiometer and RGB
LED. The purpose of these lines is to avoid confusion, with the PINs, for beginners.
Next, we start serial port communication, as on line 9, with the baud rate of 115200.
To take the potentiometer input, we need to initialize the pins by giving the following
commands:
1 pinMode (POT, INPUT) ;
2 pinMode (RGB_RED, OUTPUT) ;
3 pinMode (RGB_GREEN, OUTPUT) ;
4 pinMode (RGB_BLUE, OUTPUT) ;

where pinMode command is used to configure the specified pin as an input


or an output pin. The first argument for the above command corresponds to the
pin number and second argument corresponds to the mode of operation. In this
experiment, we configure digital pin 2 as an input pin while digital pins 9, 10, and
11 as output pins. Next, we check the value of potentiometer using analogRead
command for 10 iterations. These values range from 0 to 1023. Depending on the
read value, we turn on and turn off the Red, Green or Blue LED. For example,
when the position of the potentiometer corresponds to the values between 0 and
319, inclusive, we turn on the Red LED, keep it on for 1000 ms and then turn it off.
This functionality is carried out by,
1 i f ( v a l >= 0 & v a l < 3 2 0 ) { // t h r e s h o l d 1
2 d i g i t a l W r i t e (RGB_RED, HIGH) ;
3 delay (1000) ;
4 d i g i t a l W r i t e (RGB_RED, LOW) ;

In a similar manner, we check the potentiometer values and correspondingly turn


on and off the Green and Blue LEDs. Note that, we have used if and else if
statements to check the conditions. While running this experiment, the readers must
rotate the knob of the potentiometer and observe the change in the color of the RGB
LED.

7.3.2 Arduino Code


Arduino Code 7.1 Turning on LEDs depending on the potentiometer threshold.
Available at Origin/user-code/pot/arduino/pot-threshold/pot-thre
shold.ino, see Footnote 2 on page 2.
1 const i n t POT = 2 ;
2 const i n t RGB_RED = 1 1 ;
3 const i n t RGB_GREEN = 1 0 ;
7.4. Reading the potentiometer from Scilab 87

4 const i n t RGB_BLUE = 9 ;
5 int val = 0 ;
6 int i = 0 ;
7 void s e t u p ( ) {
8 S e r i a l . begin (115200) ;
9 pinMode (POT, INPUT) ;
10 pinMode (RGB_RED, OUTPUT) ;
11 pinMode (RGB_GREEN, OUTPUT) ;
12 pinMode (RGB_BLUE, OUTPUT) ;
13 f o r ( i = 0 ; i < 2 0 ; i ++){
14 v a l = analogRead (POT) ;
15 S e r i a l . println ( val ) ;
16 i f ( v a l >= 0 & v a l < 3 2 0 ) { // t h r e s h o l d 1
17 d i g i t a l W r i t e (RGB_RED, HIGH) ;
18 delay (1000) ;
19 d i g i t a l W r i t e (RGB_RED, LOW) ;
20 } e l s e i f ( v a l >= 320 & v a l < 9 0 0 ) { // t h r e s h o l d 2
21 d i g i t a l W r i t e (RGB_GREEN, HIGH) ;
22 delay (1000) ;
23 d i g i t a l W r i t e (RGB_GREEN, LOW) ;
24 } e l s e i f ( v a l >= 900 & v a l <= 1 0 2 3 ) { // t h r e s h o l d 3
25 d i g i t a l W r i t e (RGB_BLUE, HIGH) ;
26 delay (1000) ;
27 d i g i t a l W r i t e (RGB_BLUE, LOW) ;
28 }
29 }
30 }
31 void l o o p ( ) {
32 }

7.4 Reading the potentiometer from Scilab


7.4.1 Reading the potentiometer
In this section, we will use a Scilab script to read the potentiometer values. Based on
the acquired potentiometer values, we will change the state of the RGB 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.2
before getting started.
As explained earlier, the potentiometer values range from 0 to 1023. We will
divide this entire range into 3 bands, 0-319, 320-900, and 901-1023. For each read
value, we use an if elseif statement and correspondingly turn on either the Red,
Green or Blue LED. The code for this experiment is given in Scilab Code 7.1. We
start the experiment by opening the serial port for communication between Scilab
88 7. Interfacing a Potentiometer

and the Arduino Uno board. Then, we read the analog input at pin 2 using,
1 v a l = cmd_analog_in ( 1 , 2 )

where the first argument is for the kit number and the second argument corresponds
to the analog pin to be read. Next, we compare the read values with the set threshold,
and then turn on and off the corresponding LED. For example,
1 i f ( v a l >= 0 & v a l < 3 2 0 ) then // t h r e s h o l d 1
2 cmd_digital_out ( 1 , 1 1 , 1 )
3 sleep (1000)
4 cmd_digital_out ( 1 , 1 1 , 0 )

where cmd_digital_out is used to set the pin 11 high (1) or low (0). We used
sleep(1000) to retain the LED in the on state for 1000 milliseconds. A similar
check is done for the other two bands. While running this experiment, the readers
must rotate the knob of the potentiometer and observe the change in the color of
the RGB LED.

7.4.2 Scilab Code


Scilab Code 7.1 Turning on LEDs depending on the potentiometer threshold. Avail-
able at Origin/user-code/pot/scilab/pot-threshold.sce, see Foot-
note 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; / / p o r t 2 , baud r a t e 1 1 5 2 0 0
2 i f ok ~= 0 then e r r o r ( ’ Unable t o open s e r i a l port , p l e a s e check ’ ) ; end
3 f o r x = 1 : 2 0 / / Run f o r 2 0 i t e r a t i o n s
4 v a l = cmd_analog_in ( 1 , 2 )
5 disp ( val )
6 i f ( v a l >= 0 & v a l < 3 2 0 ) then // t h r e s h o l d 1
7 cmd_digital_out ( 1 , 1 1 , 1 )
8 sleep (1000)
9 cmd_digital_out ( 1 , 1 1 , 0 )
10 e l s e i f ( v a l >= 320 & v a l <= 9 0 0 ) // t h r e s h o l d 2
11 cmd_digital_out ( 1 , 1 0 , 1 )
12 sleep (1000)
13 cmd_digital_out ( 1 , 1 0 , 0 )
14 e l s e i f ( v a l > 900 & v a l <= 1 0 2 3 ) // t h r e s h o l d 3
15 cmd_digital_out ( 1 , 9 , 1 )
16 sleep (1000)
17 cmd_digital_out ( 1 , 9 , 0 )
18 end
19 end
20 close_serial (1) ;
7.5. Reading the potentiometer from Xcos 89

Figure 7.3: Turning LEDs on through Xcos depending on the potentiometer thresh-
old. This is what one sees when Origin/user-code/pot/scilab/pot-thre
shold.zcos, see Footnote 2 on page 2, is invoked.

7.5 Reading the potentiometer from Xcos


In this section, we discuss how to read the potentiometer values using Xcos blocks.
When the file required for this experiment is invoked, one gets the GUI as in Fig. 7.3.
In the caption of this figure, one can see where to locate the file. The reader should
go through the instructions given in Sec. 3.3 before getting started.
In this experiment, the block Analog Read Pin 2 performs the read operation
from pin 2. The threshold is set using the block, Dynamic. Depending on the
condition met, a 1 or 0 is given to pin 9, 10 or 11.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or double
click. The values for each block is tabulated in Table 7.1. All other parameters are
to be left unchanged.
Note that, when the potentiometer value read by Scilab crosses either of the
thresholds, color of the LED changes. This can be observed by rotating the knob of
the potentiometer.
90 7. Interfacing a Potentiometer

Table 7.1: Xcos parameters to turn on different LEDs depending on the potentiome-
ter value

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
CONST_m Constant Value 1, 0
DIGITAL_WRITE_SB Digital Pin 9(blue)
Digital Pin 10(green)
Digital Pin 11(red)
Arduino card number 1
ANALOG_READ_SB analog pin 2
Arduino card number 1
SWITCH2_m Datatype 1
Pass first input 1
threshold 0
use zero crossing 1
SWITCH2_m Datatype 1
Pass first input 0
threshold 320
use zero crossing 1
SWITCH2_m Datatype 1
Pass first input 0
threshold 900
use zero crossing 1
RELATIONALOP Operator 4
zero crossing 0
Datatype 1

Exercise 7.1 List out the applications in day to day life where potentiometer
is being used/can be used? For example, old fan regulators used potentiometer
to change the fan speed.
Chapter 8

Interfacing a Thermistor

A thermistor, usually made of semiconductors or metallic oxides, is a temperature


dependent/sensitive resistor. Depending on the temperature in the vicinity of the
thermistor, its resistance changes. Thermistors are available in two types, NTC
and PTC. NTC stands for Negative Temperature Coefficient and PTC for Positive
Temperature Coefficient. In NTC thermistors, the resistance decreases with the
increase in temperature and vice versa. Whereas, for PTC types, the resistance
increases with an increase in temperature and vice versa. The temperature ranges,
typically, from −55◦ Celsius to +125◦ Celsius.
Thermistors are available in a variety of shapes such as beads, rods, flakes, and
discs. Due to their compact size and low cost, they are widely used in the applica-
tions where even imprecise temperature sensing is sufficient. They, however, suffer
from noise and hence need noise compensation. In this chapter we shall interface a
thermistor with the Arduino Uno board.

8.1 Preliminaries
A typical thermistor and its symbolic representation are shown in 8.1a and 8.1b
respectively. The thermistor is available on the shield provided with the kit. It is
a bead type thermistor having a resistance of 10k at room temperature. A voltage
divider network is formed using thermistor and another fixed 10k resistor. A voltage
of 5 volts is applied across the series combination of the thermistor and the fixed 10k
resistor. Voltage across the fixed resistor is sensed and is given to the ADC via pin
4. Hence at room temperature, both the resistors offer 10k resistance resulting in
dividing the 5V equally. A buzzer is also connected on pin 3 which is a digital output
pin. Connections for this experiment are shown in 8.2a and 8.2b. Nevertheless, the
user doesn’t need to connect any wire or component explicitly.
92 8. Interfacing a Thermistor

(a) Pictorial representation of a thermistor [15] (b) Symbolic representation of


a thermistor

Figure 8.1: Pictorial and symbolic representation of a thermistor

(a) Thermistor connection diagram (b) Buzzer connection diagram

Figure 8.2: Internal connection diagrams for thermistor and buzzer on the shield
8.2. Connecting a thermistor with Arduino Uno using a breadboard 93

Figure 8.3: A thermistor to read its values with Arduino Uno using a breadboard

8.2 Connecting a thermistor 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 a thermistor, and you want to connect it with Arduino Uno
on a breadboard, please refer to Fig. 8.3. The connections given in this figure can
be used to read values from the thermistor connected to analog pin 4 on Arduino
Uno board. As shown in Fig. 8.3, one leg of the thermistor is connected to 5V on
Arduino Uno and the other leg to the analog pin 4 on Arduino Uno. A resistor
is also connected to the same leg and grounded. From Fig. 8.2a and Fig. 8.3, one
can infer that a resistor along with the thermistor is used to create a voltage divider
circuit. The varying resistance of the thermistor is converted to a varying voltage.
94 8. Interfacing a Thermistor

Figure 8.4: A thermistor to control a buzzer with Arduino Uno using a breadboard

Finally, this voltage is used by the analog pin 4 of Arduino Uno in its logic.
The connections shown in Fig. 8.4 can be used to control a buzzer, depending
on the values from the thermistor. As shown in Fig. 8.4, digital pin 3 on Arduino
Uno is connected to the one of the legs of the buzzer. Another leg of the buzzer is
connected to GND of Arduino Uno.

8.3 Interfacing the thermistor from the Arduino IDE


8.3.1 Interfacing the thermistor
In this section we will learn how to read values from the thermistor connected at
pin 4 of the Arduino Uno board. We shall also see how to drive a buzzer depending
upon the thermistor values. 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 values from thermistor is given in Arduino Code 8.1.
The Arduino IDE based command for the analog read functionality is given
by.
1 v a l = analogRead (A4) ; / / r e a d v a l u e f r o m t h e r m i s t o r
8.3. Interfacing the thermistor from the Arduino IDE 95

where A4 represents the analog pin 4 to be read. The read value is stored in
variable val and is displayed using
1 S e r i a l . p r i n t l n ( v a l ) ; // d i s p l a y

The command on next line


1 delay (500) ;

is used to put a delay of 500 milliseconds. This is to avoid very fast display
of the read values. The entire reading and display operation is carried out 40
times.
The values can be observed over the Serial Monitor of Arduino IDE. The
numbers displayed range from 0 to 1023. At room temperature you may get the
output of ADC around 500. If a heating or cooling source is available, one can
observe the increase or decrease in the ADC output. Although the thermistor
is of NTC type, the ADC output increases with increase in temperature. This
is because the voltage across the fixed resistor is sensed.
While running this experiment, the readers should try holding (or rubbing)
the thermistor with their fingertips. Doing so will transfer heat from the per-
son holding the thermistor, thereby raising the temperature of the thermistor.
Accordingly, they should observe the change in the thermistor values on the
Serial Monitor.

2. In this experiment, we will turn the buzzer on depending on the temperature


sensed by the thermistor. This experiment can be considered as a simple fire
alarm circuit that detects fires based on a sudden change in temperature and
activates the buzzer.
The program for this is available at Arduino Code 8.2. We shall use the ADC
output to carry this out. The buzzer is connected to pin 3, which is a digital
output pin. The ADC output value is displayed on the serial monitor. At
the same time, it is compared with a user-defined threshold, which has been
set as 550 in this experiment. One may note that this threshold would vary
according to the location and time of performing this experiment. Accordingly,
the readers are advised to change this threshold in Arduino Code 8.2. For
testing purposes, one may note the normal thermistor readings generated from
the execution of Arduino Code 8.1 and set a threshold that is approximately
10 more than these readings.
In this experiment, as soon as the ADC output exceeds 550, the buzzer is given
a digital high signal, turning it on. The following lines of code perform this
comparison and sending a HIGH signal to digital pin 3 on Arduino Uno:
96 8. Interfacing a Thermistor

1 i f ( val > 550)


2 {
3 d i g i t a l W r i t e ( 3 , HIGH) ; / / Turn ON b u z z e r
4 }
5 else
6 {
7 d i g i t a l W r i t e ( 3 , LOW) ; / / Turn OFF b u z z e r
8 }

A delay of half a second is introduced before the next value is read. While
running this experiment, the readers should try holding (or rubbing) the ther-
mistor with their fingertips. Doing so will transfer heat from the person holding
the thermistor, thereby raising the temperature of the thermistor. Accordingly,
they should observe whether the threshold of 550 is achieved and the buzzer
is enabled.

Note: Once the thermistor value reaches 550 (the threshold), the value will
remain the same (unless it is cooled). Therefore, the buzzer will continu-
ously produce the sound, which might be a bit annoying. To get rid of this,
the readers are advised to execute some other code on Arduino Uno like Ar-
duino Code 8.1.

Exercise 8.1 Carry out the following exercise:

1. Put the thermistor in the vicinity of an Ice bowl. Take care not to wet the
shield while doing so. Note down the ADC output value for 0◦ Celsius.

8.3.2 Arduino Code


Arduino Code 8.1 Read and display the thermistor values. Available at Origi
n/user-code/thermistor/arduino/therm-read/therm-read.ino, see
Footnote 2 on page 2.
1 int val ;
2 int i ;
3
4 void s e t u p ( )
5 {
6 S e r i a l . begin (115200) ;
7 f o r ( i = 1 ; i <= 2 0 ; i ++)
8 {
8.3. Interfacing the thermistor from the Arduino IDE 97

9 v a l = analogRead (A4) ; / / r e a d v a l u e f r o m t h e r m i s t o r
10 S e r i a l . p r i n t l n ( v a l ) ; // d i s p l a y
11 delay (500) ;
12 }
13
14 }
15
16 void l o o p ( )
17 {
18 }

Arduino Code 8.2 Turning the buzzer on using the thermistor values read by
ADC. Available at Origin/user-code/thermistor/arduino/therm-buzz
er/therm-buzzer.ino, see Footnote 2 on page 2.

1 int val ;
2 int i ;
3
4 void s e t u p ( )
5 {
6 pinMode ( 3 , OUTPUT) ;
7 S e r i a l . begin (115200) ;
8
9 f o r ( i = 1 ; i <= 2 0 ; i ++)
10 {
11 v a l = analogRead (A4) ; / / r e a d v a l u e f r o m t h e r m i s t o r
12 S e r i a l . p r i n t l n ( v a l ) ; // d i s p l a y
13
14 i f ( val > 550)
15 {
16 d i g i t a l W r i t e ( 3 , HIGH) ; / / Turn ON b u z z e r
17 }
18 else
19 {
20 d i g i t a l W r i t e ( 3 , LOW) ; / / Turn OFF b u z z e r
21 }
22 delay (500) ;
23 }
24 d i g i t a l W r i t e ( 3 , LOW) ; / / Turn OFF b u z z e r
25 }
26
27 void l o o p ( )
28 {
29 }
98 8. Interfacing a Thermistor

8.4 Interfacing the thermistor from Scilab


8.4.1 Interfacing the thermistor
In this section we will explain a Scilab script to read the thermistor values. Based
on the acquired values, we will change the state of the buzzer. 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 thermistor values and display it in
Scilab Console. The code for this experiment is given in Scilab Code 8.1. As
explained earlier in Sec. 4.4.1, we begin with serial port initialization. Then,
we read the input coming from analog pin 4 using the following command:
1 v a l = cmd_analog_in ( 1 , 4 ) ; // r e a d analog pin 4 ( thermistor )

Note that the one leg of the thermistor on the shield is connected to analog pin
4 of Arduino Uno as given in Fig. 8.2a. The read value is stored in variable
val and displayed in the Scilab Console by the following command:
1 disp ( val ) ;

where val contains the thermistor values ranging from 0 to 1023. The changes
in the thermistor resistance is sensed as a voltage change between 0 to 5V. The
ADC maps the thermistor voltage readings in to values ranging from 0 to 1023.
This means 0 for 0 volts and 1023 for 5 volts. At room temperature you may
get the output of ADC around 500. If a heating or cooling source is available,
one can observe the increase or decrease in the ADC output. To encourage the
user to have a good hands-on, we run these commands in a for loop for 20
iterations.
While running this experiment, the readers should try holding (or rubbing)
the thermistor with their fingertips. Doing so will transfer heat from the per-
son holding the thermistor, thereby raising the temperature of the thermistor.
Accordingly, they should observe the change in the thermistor values on Scilab
Console.
2. This experiment is an extension of the previous experiment. Here, we will use a
Scilab script to turn a buzzer on using the thermistor values. This experiment
can be considered as a simple fire alarm circuit that detects fires based on a
sudden change in temperature and activates the buzzer.
The program for this is available at Scilab Code 8.2. As explained earlier, the
ADC maps the thermistor voltage readings in to values ranging from 0 to 1023.
8.4. Interfacing the thermistor from Scilab 99

This means 0 for 0 volts and 1023 for 5 volts. In this experiment we compare
the ADC output value with a user-defined threshold, which has been set as 550
in this experiment. One may note that this threshold would vary according to
the location and time of performing this experiment. Accordingly, the readers
are advised to change this threshold in Scilab Code 8.2. For testing purposes,
one may note the normal thermistor readings generated from the execution of
Scilab Code 8.1 and set a threshold that is approximately 10 more than these
readings.
In this experiment, as soon as the value exceeds 550, the buzzer is turned on.
The following lines of code perform this comparison and sending a HIGH signal
to digital pin 3 on Arduino Uno:
1 i f ( val > 550) // S e t t i n g Threshold value of
550
2 cmd_digital_out ( 1 , 3 , 1 ) / / Turn ON BUZZER
3 else
4 cmd_digital_out ( 1 , 3 , 0 ) / / Turn OFF BUZZER
5 end

A delay of half a second is introduced before the next value is read. While
running this experiment, the readers should try holding (or rubbing) the ther-
mistor with their fingertips. Doing so will transfer heat from the person holding
the thermistor, thereby raising the temperature of the thermistor. Accordingly,
they should observe whether the threshold of 550 is achieved and the buzzer
is enabled.

Note: Once the thermistor value reaches 550 (the threshold), the value will
remain the same (unless it is cooled). Therefore, the buzzer will continuously
produce the sound, which might be a bit annoying. To get rid of this, the read-
ers are advised to execute some other code on Arduino Uno like Scilab Code 8.1.

Exercise 8.2 Carry out the exercise below: Convert the ADC output readings
to degree Celsius. There are two ways to do so.

1. In the first method,


1
= A + B ∗ ln(R) + C ∗ (ln(R))3 (8.1)
T
equation 8.1 can be used if the value of A, B, C and R are known. The
temperature T is in kelvin and thermistor resistance R is in ohms. The
values of A, B and C can be found out by measuring thermistor resistance
against three known values of temperatures. The values of temperature
100 8. Interfacing a Thermistor

must be within the operating range and should typically include the room
temperature. Once a set of three values of T and R are known it will result
in three equations with three unknowns. The values of A, B, C can be found
out by solving the three equations simultaneously. Once the values of A, B,
C are known, the same equation can be used to directly convert resistance
to kelvin. It can be then converted to Celsius. This method is preferred
when the temperature coefficient of thermistor is not known or is known
very approximately. This method is bit cumbersome but can give accurate
temperature conversion.
2. In the second method,
 
1 1 1 R
= + ∗ ln (8.2)
T T0 β R0

equation 8.2 can be used if the value of β i.e. the Temperature Coefficient
of Resistance of the thermistor used is known. The value of β can be found
in the data sheet of the thermistor used. R is the resistance of thermistor
at temperature T in kelvin. R0 is the resistance of thermistor at room
temperature T0 in kelvin.

8.4.2 Scilab Code


Scilab Code 8.1 Read and display the thermistor values. Available at Origin/u
ser-code/thermistor/scilab/therm-read.sce, see Footnote 2 on page 2.

1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; / / P o r t 2 w i t h b a u d r a t e 1 1 5 2 0 0
2 i f ok ~= 0 then e r r o r ( ’ Unable t o open s e r i a l p o r t . P l e a s e check ’ ) end
3 for i = 1:20 / / Run f o r 2 0 i t e r a t i o n s
4 v a l = cmd_analog_in ( 1 , 4 ) ; // r e a d a n a l o g p i n 4 ( t h e r m i s t o r )
5 disp ( val ) ;
6 sleep (500) ; // Delay o f 500 m i l l i s e c o n d s
7 end
8 c = close_serial (1) ; // c l o s e s e r i a l c o n n e c t i o n

Scilab Code 8.2 Turning the buzzer on using the thermistor values read by ADC.
Available at Origin/user-code/thermistor/scilab/therm-buzzer.sc
e, see Footnote 2 on page 2.
8.5. Interfacing the thermistor from Xcos 101

1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; // p o r t 2 , b a u d r a t e 115200
2 i f ok ~= 0 then e r r o r ( ’ Unable t o open s e r i a l port , p l e a s e check ’ ) ; end
3 f o r i = 1 : 2 0 / / Run f o r 2 0 i t e r a t i o n s
4 v a l = cmd_analog_in ( 1 , 4 ) // r e a d a n a l o g p i n 4 ( t h e r m i s t o r )
5 disp ( val ) ;
6 i f ( val > 550) // S e t t i n g T h r e s h o l d v a l u e o f 550
7 cmd_digital_out ( 1 , 3 , 1 ) / / Turn ON BUZZER
8 else
9 cmd_digital_out ( 1 , 3 , 0 ) / / Turn OFF BUZZER
10 end
11 sleep (500) ;
12 end
13 cmd_digital_out ( 1 , 3 , 0 ) / / Turn OFF BUZZER
14 close_serial (1) ;

8.5 Interfacing the thermistor from Xcos


In this section, we discuss how to read and use the thermistor values using Xcos
blocks. The reader should go through the instructions given in Sec. 3.3 before getting
started.

1. First we will read the thermistor values and display it. When the file required
for this experiment is invoked, one gets the GUI as in Fig. 8.5. In the caption
of this figure, one can see where to locate the file.
As discussed in earlier chapters, we start with the initialization of the serial
port. Next, using Analog Read block, we read the values of thermistor
connected on analog pin 4. Next, we use a scope to plot the values coming
from this pin. When this Xcos file is simulated, a plot is opened, as shown in
Fig. 8.6.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 8.1. All other
parameters are to be left unchanged.
While running this experiment, the readers should try holding (or rubbing)
the thermistor with their fingertips. Doing so will transfer heat from the per-
son holding the thermistor, thereby raising the temperature of the thermistor.
Accordingly, they should observe the change in the thermistor values in the
output plot, as shown in Fig. 8.6.

2. In the second experiment, we will switch on a buzzer depending on the ther-


mistor readings (ADC output). When the file required for this experiment is
102 8. Interfacing a Thermistor

Figure 8.5: Xcos diagram to read thermistor values. This is what one sees when O
rigin/user-code/thermistor/scilab/therm-read.zcos, see Footnote 2
on page 2, is invoked.

Table 8.1: Xcos parameters to read thermistor

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 100
Sampling period(s) 0.1
ANALOG_READ_SB Analog Pin 4
Arduino card number 1
CSCOPE Ymin 200
Ymax 600
Refresh period 100
CLOCK_c Period 0.1
Initialisation Time 0

invoked, one gets the GUI as in Fig. 8.7. In the caption of this figure, one can
see where to locate the file.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 8.2. In the
CSCOPE_c block, the two values correspond to two graphs, one for digital
write and other for analog read values. All other parameters are to be left
8.5. Interfacing the thermistor from Xcos 103

Figure 8.6: Plot window in Xcos to read thermistor values

Figure 8.7: Xcos diagram to read the value of the thermistor, which is used to turn
the buzzer on. This is what one sees when Origin/user-code/thermistor/s
cilab/therm-buzzer.zcos, see Footnote 2 on page 2, is invoked.

unchanged. When this Xcos file is simulated, a plot is opened, as shown in


Fig. 8.8.
While running this experiment, the readers should try holding (or rubbing)
104 8. Interfacing a Thermistor

Table 8.2: Xcos parameters to read thermistor and switch the buzzer

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 100
Sampling period(s) 0.1
ANALOG_READ_SB Analog pin 4
Arduino card number 1
CMSCOPE Ymin 0 300
Ymax 1 600
Refresh period 100 100
CLOCK_c Period 0.1
Initialisation time 0
SWITCH2_m Datatype 1
threshold 550
pass first input if field 0
use zero crossing 1
DIGITAL_WRITE_SB Digital pin 3
Arduino card number 1

the thermistor with their fingertips. Doing so will transfer heat from the per-
son holding the thermistor, thereby raising the temperature of the thermistor.
Accordingly, they should observe whether the threshold of 550 is achieved and
the buzzer is enabled.

Note: Once the thermistor value reaches 550 (the threshold), the value will
remain the same (unless it is cooled). Therefore, the buzzer will continuously
produce the sound, which might be a bit annoying. To get rid of this, the
readers are advised to execute some other code on Arduino Uno like the Xcos
file shown in Fig. 8.5.
8.5. Interfacing the thermistor from Xcos 105

Figure 8.8: Plot window in Xcos to read thermistor values and the state of LED
106 8. Interfacing a Thermistor
Chapter 9

Interfacing a Servomotor

A servomotor is a very useful industrial control mechanism. Learning to control it


will be extremely useful for practitioners. In this chapter, we will explain how to
control a servomotor using the Arduino Uno board. We will begin with preliminaries
of servomotors and explain how to connect a typical servomotor to the Arduino Uno
board and shield. We will then explain how to control it through the Arduino IDE
and other open-source software tools. We will provide code for all the experiments.

9.1 Preliminaries
A servomotor is a rotary control mechanism. It can be commanded to rotate to a
specified angle. It can rotate in positive or negative direction. Using servomotors,
one can control angular position, velocity and acceleration. Servomotors are useful
in many applications. Some examples are robotics, industrial motors and printers.
Typical servomotors have a maximum range of 180◦ , although some have different
ranges6 . Servomotors typically have a position sensor, using which, rotate to the
commanded angle. The minimum angle to which a servomotor can be rotated is its
least count, which varies from one model to another. Low cost servomotors have a
large least count, say, of the order of 10◦ .
A servomotor typically comes with three terminals for the following three signals:
position signal, Vcc and ground. Position signal means that this terminal should be
connected to one of the PWM (Pulse Width Modulation) pins [16] on Arduino Uno.
This book uses PWM pin 5 for this purpose. Rest two terminals (Vcc and ground)
need to be connected to 5V and GND on Arduino Uno. Table 9.1 summarizes these
connections.
6
All the angles in a servomotor are absolute angles, with respect to a fixed reference point, which
can be taken as 0◦ .
108 9. Interfacing a Servomotor

Figure 9.1: Connecting servomotor to the shield attached on Arduino Uno

Table 9.1: Connecting a typical servomotor to Arduino Uno board

Servomotor terminal Arduino board


Position signal (orange or yellow) 5
Vcc (red or orange) 5V
Ground (black or brown) GND

We now explain how to connect a typical servomotor to the shield attached on


the Arduino Uno board. On the shield, there is a three-pin header at one of the ends.
The pins of this header have been marked as 1, 2, and 3. These pins: 1, 2, and 3 are
internally connected to 5V, PWM pin 5, and GND on Arduino Uno respectively. As
discussed before, a typical servomotor has three terminals. Thus, the readers need to
connect these three terminals with the three-pin header, as shown in Fig. 9.1 before
running the experiments given in this chapter.

9.2 Connecting a servomotor 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
9.3. Controlling the servomotor through the Arduino IDE 109

Figure 9.2: A servomotor with Arduino Uno using a breadboard

Tricolor LED and Push button.


In case you have a servomotor and want to connect it with Arduino Uno on a
breadboard, please refer to Fig. 9.2. As shown in Fig. 9.2, there is a servomotor
with three terminals. These terminals are used for the same three signals, as that
explained in Sec. 9.1. The connections shown in Fig. 9.3 can be used to control the
position of the servomotor, depending on the values coming from a potentiometer.
As shown in Fig. 9.3, analog pin 2 on Arduino Uno is connected to the middle leg
of the potentiometer. Rest of the connections are same as that in Fig. 9.2.

9.3 Controlling the servomotor through the Arduino IDE


9.3.1 Controlling the servomotor
In this section, we will describe some experiments that will help rotate the servomotor
based on the command given from 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
110 9. Interfacing a Servomotor

Figure 9.3: A servomotor and a potentiometer with Arduino Uno using a breadboard

should go through the instructions given in Sec. 3.1 before getting started.

1. In the first experiment, we will move the servomotor by 30◦ . Arduino Code 9.1
has the required code for this. This code makes use of a library named Servo
[17]. Thus, we include its header file at the top of Arduino Code 9.1:
1 #include <Servo . h>

Next, we create a Servo object and call it myservo, as shown below:


1 Servo myservo ; // create servo object to control a servo

Most Arduino boards allow the creation of 12 servo objects. Next, we initial-
ize the port for serial communication at data rate of 115200 bits per second.
Following to this, we mention the pin to which the servo is attached, as shown
below:
1 myservo . a t t a c h ( 5 ) ; / / a t t a c h t h e s e r v o o b j e c t on t o p i n 5

With this, we issue the command to rotate the servomotor by 30◦ followed by
a delay of 1000 milliseconds:
1 myservo . w r i t e ( 3 0 ) ; / / t e l l servo to r o t a t e by 3 0 d e g r e e s
2 delay (1000) ;
9.3. Controlling the servomotor through the Arduino IDE 111

At last, we detach the servomotor.


Once this code is executed, the servomotor would move by 30◦ , as commanded.
What happens if this code is executed once again? The motor will not move at
all. What is the reason? Recall that what we assign to the motor are absolute
positions, with respect to a fixed origin. As a result, there will be no change
at all.

2. In the second experiment, we move the motor by 90◦ in the forward direction
and 45◦ in the reverse direction. This code is given in Arduino Code 9.2. In
this code, we have added a delay of 1000 milliseconds between the two instances
of rotating the servomotor:
1 myservo . w r i t e ( 9 0 ) ; / / t e l l servo to r o t a t e by 9 0 d e g r e e s
2 delay (1000) ;
3 myservo . w r i t e ( 4 5 ) ;

What is the reason behind this delay? If the delay were not there, the motor
will move only by the net angle of 90 − 45 = 45 degrees. The reader should
verify this by commenting on the delay command.

3. In the third experiment, we move the motor in increments of 20◦ . This is


achieved by the for loop, as in Arduino Code 9.3. Both i, the loop variable
and angle, the variable to store angle, are declared as int in this code. The
code helps the motor move in steps of 20◦ all the way to 180◦ .

4. Finally, in the last experiment, we read the potentiometer value from the shield
and use it to drive the servomotor, see Arduino Code 9.4. The resistance of
the potentiometer is represented in 10 bits. As a result, the resistance value
could be any one of 1024 values, from 0 to 1023. This entire range is mapped
to 180◦ , as shown below:
1 v a l = analogRead ( p o t p i n ) ; / / r e a d s a v a l u e i n ( 0 , 1 0 2 3 ) t h r o u g h
pot
2 v a l = map( v a l , 0 , 1 0 2 3 , 0 , 1 8 0 ) ; / / maps i t i n t h e r a n g e ( 0 , 1 8 0 )
degrees
3 myservo . w r i t e ( v a l ) ; / / m o v e s t h e m o t o r t o t h e mapped
degree

By rotating the potentiometer, one can make the motor move by different
amounts.
As mentioned in Chapter 7, the potentiometer on the shield is connected to
analog pin 2 on Arduino Uno. Through this pin, the resistance of the poten-
tiometer, in the range of 0 to 1023, depending on its position, is read. Thus,
by rotating the potentiometer, we make different values appear on pin 2. This
112 9. Interfacing a Servomotor

value is used to move the servo. For example, if the resistance is half of the
total, the servomotor will go to 90◦ and so on. The servomotor stops for 500
milliseconds after every move. The loop is executed for 50 iterations. During
this period, the servomotor keeps moving as dictated by the resistance of the
potentiometer. While running this experiment, the readers must rotate the
knob of the potentiometer and observe the change in the position (or angle) of
the servomotor.

Exercise 9.1 Let us carry out this exercise:

1. In Arduino Code 9.3, the loop parameter i starts from 1. From what angle
will the motor start? If one wants the motor to start from 0◦ , what should
one do?
2. How does one find the least count of the servomotor? If the variable angle
is chosen to be less than this least count in Arduino Code 9.3, what happens?
3. What happens if 180 in Line 10 of Arduino Code 9.4 is changed to 90?
What does the change 180 to 90 mean?

9.3.2 Arduino Code


Arduino Code 9.1 Rotating the servomotor to a specified degree. Available at
Origin/user-code/servo/arduino/servo-init/servo-init.ino, see
Footnote 2 on page 2.
1 #include <Servo . h>
2 Servo myservo ; / / c r e a t e s e r v o o b j e c t t o c o n t r o l a s e r v o
3 void s e t u p ( ) {
4 S e r i a l . begin (115200) ;
5 myservo . a t t a c h ( 5 ) ; / / a t t a c h t h e s e r v o o b j e c t on t o p i n 5
6 myservo . w r i t e ( 3 0 ) ; / / t e l l s e r v o t o r o t a t e by 3 0 d e g r e e s
7 delay (1000) ;
8 myservo . d e t a c h ( ) ;
9 }
10 void l o o p ( ) {
11 }

Arduino Code 9.2 Rotating the servomotor to a specified degree and reversing.
Available at Origin/user-code/servo/arduino/servo-reverse/servo-
reverse.ino, see Footnote 2 on page 2.
9.3. Controlling the servomotor through the Arduino IDE 113

1 #include <Servo . h>


2 Servo myservo ; / / c r e a t e s e r v o o b j e c t t o c o n t r o l a s e r v o
3 void s e t u p ( ) {
4 S e r i a l . begin (115200) ;
5 myservo . a t t a c h ( 5 ) ; / / a t t a c h t h e s e r v o o b j e c t on t o p i n 5
6 myservo . w r i t e ( 9 0 ) ; / / t e l l s e r v o t o r o t a t e by 9 0 d e g r e e s
7 delay (1000) ;
8 myservo . w r i t e ( 4 5 ) ;
9 delay (1000) ;
10 myservo . d e t a c h ( ) ;
11 }
12 void l o o p ( ) {
13 }

Arduino Code 9.3 Rotating the servomotor in increments. Available at Origin/


user-code/servo/arduino/servo-loop/servo-loop.ino, see Footnote 2
on page 2.
1 #include <Servo . h>
2 Servo myservo ; / / c r e a t e s e r v o object to control a servo
3 int angle = 2 0 ;
4 int i = 0 ;
5 void s e t u p ( ) {
6 f o r ( i = 1 ; i < 1 0 ; i ++) {
7 S e r i a l . begin (115200) ;
8 myservo . a t t a c h ( 5 ) ; // a t t a c h t h e s e r v o o b j e c t on t o p i n 5
9 myservo . w r i t e ( a n g l e ∗ i ) ; / / t e l l s e r v o t o r o t a t e by 2 0 d e g r e e s
10 delay (1000) ; // waits for a sec
11 }
12 myservo . d e t a c h ( ) ;
13 }
14 void l o o p ( ) {
15 }

Arduino Code 9.4 Rotating the servomotor through the potentiometer. Available
at Origin/user-code/servo/arduino/servo-pot/servo-pot.ino, see
Footnote 2 on page 2.
1 #include <Servo . h>
2 Servo myservo ; / / c r e a t e s e r v o o b j e c t t o c o n t r o l a s e r v o
3 int potpin = 2 ; // a n a l o g p i n u s ed t o c o n n e c t t h e p o t e n t i o m e t e r
4 int val ; // v a r i a b l e t o r e a d t h e v a l u e from t h e a n a l o g p i n
5 int i ;
6 void s e t u p ( ) {
7 S e r i a l . begin (115200) ;
8 myservo . a t t a c h ( 5 ) ; / / a t t a c h t h e s e r v o o b j e c t on t o p i n 5
9 f o r ( i = 0 ; i < 5 0 ; ++i ) {
10 v a l = analogRead ( p o t p i n ) ; / / r e a d s a v a l u e i n ( 0 , 1 0 2 3 ) t h r o u g h p o t
114 9. Interfacing a Servomotor

11 v a l = map( v a l , 0 , 1 0 2 3 , 0 , 1 8 0 ) ; / / maps i t i n t h e r a n g e ( 0 , 1 8 0 )
degrees
12 myservo . w r i t e ( v a l ) ; / / m o v e s t h e m o t o r t o t h e mapped d e g r e e
13 delay (500) ; // w a i t s f o r a s e c o n d f o r s e r v o t o r e a c h
14 }
15 myservo . d e t a c h ( ) ;
16 }
17 void l o o p ( ) {
18 }

9.4 Controlling the servomotor through Scilab


9.4.1 Controlling the servomotor
In this section, we discuss how to carry out the experiments of the previous section
from Scilab. 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. The first experiment makes the servomotor move by 30◦ . The code for this
experiment is given in Scilab Code 9.1. As explained earlier in Sec. 4.4.1, we
begin with serial port initialization. Next, we attach the servomotor by issuing
the command given below:
1 cmd_servo_attach ( 1 , 1 ) / / To a t t a c h t h e motor to p i n 5

As shown above, the servomotor is attached on board 1 (the first argument)


to pin 1 (the second argument). In the Scilab-Arduino toolbox discussed in
Sec. 3.2.3, pin 1 and pin 5 are connected. As a result, we connect the wire
physically to pin 5, which is achieved by the shield as discussed in Sec. 9.1.
With this, we issue the command to move the servomotor by 30◦ followed by
a delay of 1000 milliseconds:
1 cmd_servo_move ( 1 , 1 , 3 0 ) / / t e l l servo to r o t a t e by 3 0 d e g r e e s
2 sleep (1000)

At last, we detach the servomotor followed by closing the serial port.


Once this code is executed, the servomotor would move by 30◦ , as commanded.
What happens if this code is executed once again? The motor will not move at
all. What is the reason? Recall that what we assign to the motor are absolute
positions, with respect to a fixed origin. As a result, there will be no change
at all.
9.4. Controlling the servomotor through Scilab 115

2. In the second experiment, we move the servomotor by 90◦ in the forward


direction and 45◦ in the reverse direction. This code is given in Scilab Code 9.2.
In this code, we have added a delay of 1000 milliseconds between the two
instances of moving the servomotor:
1 cmd_servo_move ( 1 , 1 , 9 0 ) / / Move t h e s e r v o t o 9 0 d e g r e e
2 s l e e p (1000) // be t h e r e f o r one s e c o n d
3 cmd_servo_move ( 1 , 1 , 4 5 ) / / Move t h e s e r v o t o 4 5 d e g r e e

What is the reason behind this delay? If the delay were not there, the motor
will move only by the net angle of 90 − 45 = 45 degrees. The reader should
verify this by commenting on the delay command.

3. In the third experiment, we move the motor in increments of 20◦ . This is


achieved by the for loop, as in Scilab Code 9.3. The code helps the motor
move in steps of 20◦ all the way to 180◦ .

4. Finally, in the last experiment, we read the potentiometer value from the shield
and use it to drive the servomotor, see Scilab Code 9.4. The resistance of the
potentiometer is represented in 10 bits. As a result, the resistance value could
be any one of 1024 values, from 0 to 1023. This entire range is mapped to
180◦ , as shown below:
1 v a l = cmd_analog_in ( 1 , 2 ) / / Read p o t n t i o m e t e r v a l u e
2 v a l = f l o o r ( v a l ∗(180/1023) ) // S c a l e P o t e n t i o m e t e r v a l u e t o
0 −180
3 cmd_servo_move ( 1 , 1 , v a l ) / / Command t h e s e r v o m o t o r

By rotating the potentiometer, one can make the motor move by different
amounts.
As mentioned in Chapter 7, the potentiometer on the shield is connected to
analog pin 2 on Arduino Uno. Through this pin, the resistance of the poten-
tiometer, in the range of 0 to 1023, depending on its position, is read. Thus,
by rotating the potentiometer, we make different values appear on pin 2. This
value is used to move the servo. For example, if the resistance is half of the
total, the servomotor will go to 90◦ and so on. The servomotor stops for 500
milliseconds after every move. The loop is executed for 50 iterations. During
this period, the servomotor keeps moving as dictated by the resistance of the
potentiometer. While running this experiment, the readers must rotate the
knob of the potentiometer by a fixed amount and observe the change in the
position (or angle) of the servomotor.
116 9. Interfacing a Servomotor

9.4.2 Scilab Code


Scilab Code 9.1 Rotating the servomotor to a specified degree. Available at Ori
gin/user-code/servo/scilab/servo-init.sce, see Footnote 2 on page 2.

1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) / / At p o r t 2 w i t h baud r a t e o f 1 1 5 2 0 0
2 i f ok ~= 0 e r r o r ( ’ Check t h e s e r i a l p o r t and t r y a g a i n ’ ) ; end
3 cmd_servo_attach ( 1 , 1 ) / / To a t t a c h t h e m o t o r t o p i n 5
4 cmd_servo_move ( 1 , 1 , 3 0 ) / / t e l l s e r v o t o r o t a t e by 3 0 d e g r e e s
5 sleep (1000)
6 cmd_servo_detach ( 1 , 1 ) // Detach t h e motor
7 close_serial (1)

Scilab Code 9.2 Rotating the servomotor to a specified degree and reversing. Avail-
able at Origin/user-code/servo/scilab/servo-reverse.sce, see Foot-
note 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) / / C o n n e c t t o A r d u i n o a t p o r t 2
2 i f ok ~= 0 e r r o r ( ’ Check t h e s e r i a l p o r t and t r y a g a i n ’ ) ; end
3 cmd_servo_attach ( 1 , 1 ) / / A t t a c h t h e m o t o r t o p i n 5 . 1 means 9
4 cmd_servo_move ( 1 , 1 , 9 0 ) / / Move t h e s e r v o t o 9 0 d e g r e e
5 s l e e p (1000) // be t h e r e f o r one s e c o n d
6 cmd_servo_move ( 1 , 1 , 4 5 ) / / Move t h e s e r v o t o 4 5 d e g r e e
7 sleep (1000) // be t h e r e f o r one s e c o n d
8 cmd_servo_detach ( 1 , 1 ) // Detach t h e motor
9 close_serial (1) / / To c l o s e t h e c o n n e c t i o n s a f e l y

Scilab Code 9.3 Rotating the servomotor in steps of 20◦ . Available at Origin/u
ser-code/servo/scilab/servo-loop.sce, see Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) ; / / At p o r t 2 w i t h b a u d r a t e o f 1 1 5 2 0 0
2 i f ok ~= 0 e r r o r ( ’ Check t h e s e r i a l p o r t and t r y a g a i n ’ ) ; end
3 angle = 20; / / A n g l e by w h i c h i t h a s t o move
4 for i = 0:10
5 cmd_servo_attach ( 1 , 1 ) / / A t t a c h m o t o r t o p i n 5 . 1 means p i n
9.
6 cmd_servo_move ( 1 , 1 , a n g l e ∗ i ) / / t e l l s e r v o t o r o t a t e by 2 0 d e g r e e s
7 sleep (1000) // w a i t s f o r a s e c
8 end
9 cmd_servo_detach ( 1 , 1 ) // Detach t h e motor
10 close_serial (1) ; / / To c l o s e t h e c o n n e c t i o n safely

Scilab Code 9.4 Rotating the servomotor to a degree specified by the potentiome-
ter. Available at Origin/user-code/servo/scilab/servo-pot.sce, see
Footnote 2 on page 2.
9.5. Controling the servomotor through Xcos 117

Table 9.2: Parameters to rotate the servomotor by 30◦

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
SERVO_WRITE_SB Servo number 1
Arduino card number 1
CONST_m Constant value 30

1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) / / At p o r t 2 w i t h baud r a t e o f 1 1 5 2 0 0
2 i f ok ~= 0 e r r o r ( ’ Check t h e s e r i a l p o r t and t r y a g a i n ’ ) ; end
3 cmd_servo_attach ( 1 , 1 ) / / A t t a c h t h e m o t o r t o p i n 5
4 f o r i =1:50 // 5 , 0 0 0 i t t e r a t i o n s
5 v a l = cmd_analog_in ( 1 , 2 ) / / Read p o t n t i o m e t e r v a l u e
6 v a l = f l o o r ( v a l ∗ ( 1 8 0 / 1 0 2 3 ) ) / / S c a l e P o t e n t i o m e t e r v a l u e t o 0 −180
7 cmd_servo_move ( 1 , 1 , v a l ) / / Command t h e s e r v o m o t o r
8 sleep (500) // s l e e p f o r 500 m i l l i s e c o n d s
9 end
10 cmd_servo_detach ( 1 , 1 ) / / D e t a c h t h e m o t o r
11 close_serial (1)

9.5 Controling the servomotor through Xcos


In this section, we will see how to rotate the servomotor from Scilab Xcos. We will
carry out experiments similar to the ones in earlier sections. For each, we will give
the location of the zcos file and the parameters to set. The reader should go through
the instructions given in Sec. 3.3 before getting started.

1. First we will rotate the servomotor by 30◦ . When the file required for this
experiment is invoked, one gets the GUI as in Fig. 9.4. In the caption of this
figure, one can see where to locate the file.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 9.2. All other
parameters are to be left unchanged.

2. Next, we will rotate the servomotor by 90◦ and bring it to 45◦ , all absolute
values. When the file required for this experiment is invoked, one gets the GUI
118 9. Interfacing a Servomotor

Figure 9.4: Rotating the servomotor by a fixed angle. This is what one sees when Or
igin/user-code/led/scilab/servo-init.zcos, see Footnote 2 on page 2,
is invoked.

Table 9.3: Parameters to rotate the servomotor forward and reverse

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
SERVO_WRITE_SB Servo number 1
Arduino card number 1
STEP_FUNCTION Step time 1
Initial value 90
Final value 45

as in Fig. 9.5. In the caption of this figure, one can see where to locate the file.

We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 9.3. All other
parameters are to be left unchanged.
9.5. Controling the servomotor through Xcos 119

Figure 9.5: Rotating the servomotor forward and then reverse. This is what one sees
when Origin/user-code/led/scilab/servo-reverse.zcos, see Foot-
note 2 on page 2, is invoked.

3. Next, we will rotate the servomotor in increments of 20◦ . When the file required
for this experiment is invoked, one gets the GUI as in Fig. 9.6. In the caption
of this figure, one can see where to locate the file.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 9.4. Do on
Overflow 0 means that we need to do nothing when there is an overflow.
All other parameters are to be left unchanged.
4. Finally, we will use Xcos to rotate the servomotor as per the input received
from the potentiometer. When the file required for this experiment is invoked,
one gets the GUI as in Fig. 9.7. In the caption of this figure, one can see where
to locate the file.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 9.5. All other
parameters are to be left unchanged. The ANALOG_READ_SB block reads the
value of potentiometer. Next, GAIN_f is used to convert the potentiometer
values into rotation angle by multiplying the values with 180/1023.
120 9. Interfacing a Servomotor

Figure 9.6: Rotating the servomotor in increments of 20◦ . This is what one sees
when Origin/user-code/led/scilab/servo-loop.zcos, see Footnote 2
on page 2, is invoked.

Table 9.4: Parameters to make the servomotor to sweep the entire range in incre-
ments

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
SERVO_WRITE_SB Servo number 1
CLOCK_c Period 1
Initialization time 0.1
Counter Minimum value 0
Maximum value 10
Rule 1
GAINBLK Gain 20
Do on overflow 0
9.5. Controling the servomotor through Xcos 121

Figure 9.7: Rotating the servomotor as suggested by the potentiometer. This is


what one sees when Origin/user-code/led/scilab/servo-pot.zcos, see
Footnote 2 on page 2, is invoked.

Table 9.5: Parameters to rotate the servomotor based on the input from the poten-
tiometer

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE The duration of acquisition(s) 100
Sampling period(s) 0.1
SERVO_WRITE_SB Servo number 1
ANALOG_READ_SB Analog Pin 2
Arduino card number 1
GAIN_f Gain 180/1023
122 9. Interfacing a Servomotor
Chapter 10

Interfacing a DC Motor

Motors are widely used in commercial applications. DC motor converts electric


power obtained from direct current to mechanical motion. This chapter describes
the experiments to control DC motor with Arduino Uno board. We will observe
the direction of motion of the DC motor being changed using the microcontroller
on Arduino Uno board. Control instruction will be sent to Arduino Uno using the
Arduino IDE and other open-source software tools. The experiments provided in
this chapter don’t require the shield. Therefore, the readers must remove the shield
from the Arduino Uno before moving further in this chapter. Before removing the
shield, the readers are advised to detach Arduino Uno from the computer.

10.1 Preliminaries
In order to change its direction, the sign of the voltage applied to the DC motor is
changed. For that, one needs to use external hardware called H-Bridge circuit DC
motor with Arduino Uno. H-Bridge allows direction of the current passing through
the DC motor to be changed. It avoids the sudden short that may happen while
changing the direction of current passing through the motor. It is one of the essential
circuits for the smooth operation of a DC motor. There are many manufacturers
of H-bridge circuit viz. L293D, L298, etc. Often they provide small PCB breakout
boards. These modules also provide an extra supply that is needed to drive the
DC motor. Fig. 10.1 shows the diagram of a typical breakout board containing IC
L293D, which will be used in this book. One may note that the toolboxes presented
in this book supports three types of H-Bridge circuit. Table 10.1 provides the values
to be passed for different H-Bridge circuits.
Input from Arduino Uno to H-bridge IC is in pulse width modulation (PWM)
form. PWM is a technique to generate analog voltages using digital pins. We know
124 10. Interfacing a DC Motor

Figure 10.1: L293D motor driver board

Table 10.1: Values to be passed for different H-Bridge circuits

Type of H-Bridge circuit Value


MotorShield Rev3 1
PMODHB5/L298 2
L293D 3

that Arduino Uno has digital input-output pins. When these pins are configured
as an output, they provide High (5V) or Low (0V) voltage. With PWM technique,
these pins are switched on and off iteratively and fast enough so that the voltage is
averaged out to some analog value in between 0-5V. This analog value depends on
”switch-on” time and ”switch-off” time. For example, if both ”switch-on” time and
”switch-off” time are equal, average voltage on PWM pin will be 2.5V. To enable fast
switching of digital pin, a special hardware is provided in microcontrollers. PWM
is considered as an important resource of the microcontroller system. Arduino Uno
board has 6 PWM pins (3, 5, 6, 9, 10, 11) [16]. On an original Arduino Uno board,
these pins are marked with a tilde sign next to the pin number, as shown in Fig. 10.2.
For each of these pins, the input can come from 8 bits. Thus we can generate 28 = 256
different analog values (from 0 to 255) in between 0-5V with these pins.
10.2. Controlling the DC motor from Arduino 125

Figure 10.2: PWM pins on an Arduino Uno board

We now carry out the following connections:


1. Connect input of L293D (M1_IN) pins to two of the PWM pins available on
Arduino Uno. We have used pins 9 and 10 of the Arduino Uno board.
2. Connect the output of the L293D (M1_OUT) pins directly to the 2 wires of
the DC motor. As the direction is changed during the operation, the polarity
of the connection does not matter.
3. Connect supply (Vcc) and ground (Gnd) pins of L293D to 5V and Gnd pins
of the Arduino Uno board, respectively.
A schematic of these connections is given in Fig. 10.3. The actual connections can
be seen in Fig. 10.4.

10.2 Controlling the DC motor from Arduino


10.2.1 Controlling the DC motor
In this section, we will describe some experiments that will help drive the DC motor
from the Arduino IDE. We will also give the necessary code. We will present three
experiments in this section. As mentioned earlier, the shield must be removed from
the Arduino Uno 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.
126 10. Interfacing a DC Motor

Figure 10.3: A schematic of DC motor connections

Figure 10.4: How to connect the DC motor to the Arduino Uno board

Note: The readers are advised to affix a small (very lightweight) piece of paper at
the tip of the shaft of the DC motor. That will help them observe the direction of
rotation of the DC motor while running the experiments.
10.2. Controlling the DC motor from Arduino 127

1. We now demonstrate how to drive the DC motor from the Arduino IDE. Ar-
duino Code 10.1 has the required code for this. It starts the serial port at a
baud rate of 115200. Pins 9 and 10 are declared as output pins and hence
values can be written on to them. The following lines are used to declare these
two pins as output pins:
1 pinMode ( 9 , OUTPUT) ; / / u s e p i n s 9 and 1 0 f o r m o t o r o u t p u t
2 pinMode ( 1 0 , OUTPUT) ;

Next, we write PWM 100 on pin 9 and PWM 0 on pin 10, as shown below:
1 a n a l o g W r i t e ( 9 , 1 0 0 ) ; / / PWM 1 0 0 on p i n 9 ma k es t h e m o t o r r o t a t e
2 analogWrite (10 , 0) ;

Recall from Fig. 10.4 that pins 9 and 10 are connected to the input of the
breakout board, which in turn makes the DC motor run at an intermediate
speed. Some of the breakout boards may not have enough current driving
capability and hence tend to heat up. To avoid these difficulties, the DC motor
is run at an intermediate value of PWM 100. Remember, we can increase this
value upto 255.
The line containing delay makes the previous command execute for 3 seconds.
As a result, the DC motor continues to rotate for 3 seconds. After this, we put
a 0 in both pins 9 and 10, as shown below:
1 analogWrite (9 , 0) ; / / 0 on p i n 9 s t o p s t h e motor
2 analogWrite (10 , 0) ;

With this, the motor comes to a halt.

2. It is easy to make the DC motor run in the reverse direction by interchanging


the values put on pins 9 and 10. This is done in Arduino Code 10.2. In this
code, we make the DC motor run in one direction for 3 seconds and then make
it rotate in the reverse direction for 2 seconds. The rotation in reverse direction
is achieved by putting 100 in pin 10, as shown below:
1 analogWrite (9 , 0) ; //
2 analogWrite (10 , 100) ; // Motor r u n s in the reverse direction for

Next, we release the motor by writing 0 in both pins 9 and 10, as shown below:
1 analogWrite (9 , 0) ; // Motor is stopped
2 analogWrite (10 , 0) ; //

With this, the motor comes to a halt.


128 10. Interfacing a DC Motor

3. Next, we make the DC motor run in forward and reverse directions, in a loop.
This is done through Arduino Code 10.3. We first write PWM 100 in pin 9 for
3 seconds. After that, make the motor stop for 2 seconds. Finally, make the
motor rotate in the reverse direction by writing PWM 100 in pin 10 for two
seconds. Finally, we make the motor stop for one second. The entire thing is
put in a for loop which runs for 5 iterations.

Exercise 10.1 Carry out the following exercise:

1. Try out some of the suggestions given above, i.e., removing certain numbers
from the code
2. See if the DC motor runs if you put 1 instead of 100 as the PWM value.
Explain why it does not run. Find out the smallest value at which it will
start running.

10.2.2 Arduino Code


Arduino Code 10.1 Rotating the DC motor. Available at Origin/user-code
/dcmotor/arduino/dcmotor-clock/dcmotor-clock.ino, see Footnote 2
on page 2.
1 void s e t u p ( ) {
2 S e r i a l . begin (115200) ; // s e t t h e b a u d r a t e
3 pinMode ( 9 , OUTPUT) ; / / u s e p i n s 9 and 1 0 f o r m o t o r o u t p u t
4 pinMode ( 1 0 , OUTPUT) ;
5 a n a l o g W r i t e ( 9 , 1 0 0 ) ; / / PWM 1 0 0 on p i n 9 m a k e s t h e m o t o r r o t a t e
6 analogWrite (10 , 0) ;
7 delay (3000) ; // Th i s i s a l l o w e d t o c o n t i n u e f o r 3 s e c o n d s
8 analogWrite (9 , 0) ; / / 0 on p i n 9 s t o p s t h e m o t o r
9 analogWrite (10 , 0) ;
10 }
11 void l o o p ( ) {
12 / / what is put h e r e will r u n i n an infinite loop
13 }

Arduino Code 10.2 Rotating the DC motor in both directions. Available at Ori
gin/user-code/dcmotor/arduino/dcmotor-both/dcmotor-both.ino,
see Footnote 2 on page 2.
1 void s e t u p ( ) {
2 S e r i a l . begin (115200) ; // s e t t h e b a u d r a t e
10.3. Controlling the DC motor from Scilab 129

3 pinMode ( 9 , OUTPUT) ; / / u s e p i n s 9 and 1 0 f o r m o t o r o u t p u t


4 pinMode ( 1 0 , OUTPUT) ;
5 analogWrite (9 , 100) ; // Motor r u n s a t a low s p e e d
6 analogWrite (10 , 0) ;
7 delay (3000) ; // 3 s e c o n d d e l a y
8 analogWrite (9 , 0) ; //
9 analogWrite ( 1 0 , 100) ; // Motor r u n s i n t h e r e v e r s e d i r e c t i o n f o r
10 delay (2000) ; // 2 s e c o n d s
11 analogWrite (9 , 0) ; // Motor i s s t o p p e d
12 analogWrite (10 , 0) ; //
13 }
14 void l o o p ( ) {
15 / / Code h e r e runs i n an infinite loop
16 }

Arduino Code 10.3 Rotating the DC motor in both directions in a loop. Available
at Origin/user-code/dcmotor/arduino/dcmotor-loop/dcmotor-loop
.ino, see Footnote 2 on page 2.
1 int i ;
2 void s e t u p ( ) {
3 S e r i a l . begin (115200) ; // s e t t h e b a u d r a t e
4 pinMode ( 9 ,OUTPUT) ; / / u s e p i n s 9 and 1 0 for motor output
5 pinMode ( 1 0 ,OUTPUT) ;
6 f o r ( i = 0 ; i < 4 ; i ++){
7 analogWrite (9 , 100) ; // Motor r u n s a t a low s p e e d
8 analogWrite (10 , 0) ;
9 delay (3000) ; // 3 s e c o n d delay
10 analogWrite (9 , 0) ;
11 analogWrite (10 , 0) ; // Motor s t o p s f o r
12 delay (2000) ; // 1 s e c o n d s
13 analogWrite (9 , 0) ; //
14 analogWrite (10 , 100) ; // Motor r u n s i n t h e reverse direction for
15 delay (2000) ; // 2 s e c o n d s
16 analogWrite (9 , 0) ; // Stop t h e
17 analogWrite (10 , 0) ; // motor r o t a t i n g
18 delay (1000) ; // f o r 1 s e c o n d
19 }
20 }
21 void l o o p ( ) {
22 }

10.3 Controlling the DC motor from Scilab


10.3.1 Controlling the DC motor
In this section, we discuss how to carry out the experiments of the previous section
from Scilab. We will list the same three experiments, in the same order. As men-
130 10. Interfacing a DC Motor

tioned earlier, the shield must be removed from the Arduino Uno 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.

Note: The readers are advised to affix a small (very lightweight) piece of paper at
the tip of the shaft of the DC motor. That will help them observe the direction of
rotation of the DC motor while running the experiments.

1. In the first experiment, we will learn how to drive the DC motor from Scilab.
The code for this experiment is given in Scilab Code 10.1. As explained earlier
in Sec. 4.4.1, we begin with serial port initialization. Next, the code has a
command of the following form:
cmd_dcmotor_setup ( 1 , H−B r i d g e type , Motor number ,
PWM p i n 1 , PWM p i n 2 )

As mentioned earlier, this chapter makes use of an H-Bridge circuit which


allows direction of the current passing through the DC motor to be changed.
We are using L293D as an H-Bridge circuit in this book. Thus, we will pass
the value 3 for H-Bridge type. The Scilab-Arduino toolbox, as explained in
Sec. 3.2.3, supports three types of H-Bridge circuit. Table 10.1 provides the
values to be passed for different H-Bridge circuits. Next argument in the
command given above is Motor number. Here, we pass the value 1. Finally,
we provide the PWM pins to which the DC motor is connected. As shown in
Fig. 10.4, pins 9 and 10 are connected to the input of the breakout board. As
a result, the command cmd_dcmotor_setup becomes
1 cmd_dcmotor_setup ( 1 , 3 , 1 , 9 , 1 0 ) / / S e t u p DC m o t o r o f type 3 (
L293D ) , m o t o r 1 , p i n 9 and 1 0

The next line of Scilab Code 10.1 is of the following form:


cmd_dcmotor_run ( 1 , Motor number , [ s i g n ] PWM v a l u e )

Here, we will pass the value 1 in Motor number. As mentioned earlier, for
each of the PWM pins on Arduino Uno board, the input can come from 8
bits. Thus, these pins can supply values between −255 and +255. Positive
values correspond to clockwise rotation while negative values correspond to
anti-clockwise rotation. Based on the PWM value and polarity, corresponding
analog voltage is generated. We put a PWM value of 100 to make the DC motor
run at an intermediate speed. As a result, the command cmd_dcmotor_run
becomes
10.3. Controlling the DC motor from Scilab 131

1 cmd_dcmotor_run ( 1 , 1 , 1 0 0 ) / / M o t o r 1 r u n s a t PWM 1 0 0

The above-mentioned command does not say for how long the motor should
run. This is taken care of by the sleep command, as given below:
1 sleep (3000) // Th i s is allowed to continue for 3
seconds

With this, the DC motor will run for 3000 milliseconds or 3 seconds. At last,
we release the DC motor, as shown below:
1 cmd_dcmotor_release ( 1 , 1 ) / / M o t o r 1 i s released

With the execution of this command, the PWM functionality on the Arduino
Uno pins is ceased. This has the motor number as an input parameter. At
last, we close the serial port.

Note: If the sleep command (at line 4 of Scilab Code 10.1) were not present,
the DC motor will not even run: soon after putting the value 100, the DC
motor would be released, leaving no time in between. On the other hand, if
the DC motor is not released (i.e., line number 5 of Scilab Code 10.1 being
commented), the DC motor will go on rotating. That’s why, it may be inferred
that line number 5 of Scilab Code 10.1 is mandatory for every program. We
encourage the readers to run Scilab Code 10.1 by commenting any one or two
of the lines numbered 4, 5 or 6. Go ahead and do it - you will not break
anything. At the most, you may have to unplug the USB cable connected to
Arduino Uno and restart the whole thing from the beginning.

2. It is easy to make the DC motor run in the reverse direction by changing the
sign of PWM value being written. This is done in Scilab Code 10.2. In this
code, we make the DC motor run in one direction for 3 seconds and then make
it rotate in the reverse direction for 2 seconds. The rotation in reverse direction
is achieved by putting −100 in the command cmd_dcmotor_run, as shown
below:
1 cmd_dcmotor_run ( 1 , 1 , −100) / / M o t o r 1 r u n s a t PWM −100 i n
reverse direction

After adding a sleep of 2 seconds, we release the motor by issuing the com-
mand cmd_dcmotor_release, followed by closing the serial port:
1 cmd_dcmotor_release ( 1 , 1 ) // Motor 1 i s released
2 close_serial (1) ;

With this, the motor comes to a halt.


132 10. Interfacing a DC Motor

3. Next, we make the DC motor run in forward and reverse directions, in a loop.
This is done through Scilab Code 10.3. We first write PWM +100 for 3 seconds.
After that, halt the motor for 2 seconds by writing zero PWM value. Next,
make the motor rotate in the reverse direction by writing PWM −100 for two
seconds. Next, we make the motor stop for one second. This procedure is put
in a for loop which runs for 4 iterations. At last, we release the motor by
issuing the command cmd_dcmotor_release, followed by closing the serial
port

Exercise 10.2 Carry out the following exercise:

1. Try out some of the suggestions given above, i.e., removing certain numbers
from the code.
2. See if the DC motor runs if you put 1 instead of 100 as the PWM value.
Explain why it does not run. Find out the smallest value at which it will
start running.

10.3.2 Scilab Code


Scilab Code 10.1 Rotating the DC motor. Available at Origin/user-code/d
cmotor/scilab/dcmotor-clock.sce, see Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) / /COM p o r t i s 2 and baud r a t e is
115200
2 cmd_dcmotor_setup ( 1 , 3 , 1 , 9 , 1 0 ) / / S e t u p DC m o t o r o f t y p e 3 ( L293D ) ,
m o t o r 1 , p i n 9 and 1 0
3 cmd_dcmotor_run ( 1 , 1 , 1 0 0 ) / / M o t o r 1 r u n s a t PWM 1 0 0
4 sleep (3000) // Th i s i s a l l o w e d t o c o n t i n u e f o r 3 s e c o n d s
5 cmd_dcmotor_release ( 1 , 1 ) / / M o t o r 1 i s r e l e a s e d
6 close_serial (1) ;

Scilab Code 10.2 Rotating DC motor in both directions. Available at Origin/u


ser-code/dcmotor/scilab/dcmotor-both.sce, see Footnote 2 on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) / /COM p o r t i s 2 and baud r a t e is
115200
2 cmd_dcmotor_setup ( 1 , 3 , 1 , 9 , 1 0 ) / / S e t u p DC m o t o r o f t y p e 3 ( L293D ) ,
m o t o r 1 , p i n 9 and 1 0
3 cmd_dcmotor_run ( 1 , 1 , 1 0 0 ) / / M o t o r 1 r u n s a t PWM 1 0 0
4 sleep (3000) // for 3 seconds
5 cmd_dcmotor_run ( 1 , 1 , −100) / / M o t o r 1 r u n s a t PWM −100 i n reverse
direction
10.4. Controlling the DC motor from Xcos 133

6 sleep (2000) // f o r 2 s e c o n d s
7 cmd_dcmotor_release ( 1 , 1 ) // Motor 1 i s r e l e a s e d
8 close_serial (1) ;

Scilab Code 10.3 Rotating the DC motor in both directions in a loop. Available at
Origin/user-code/dcmotor/scilab/dcmotor-loop.sce, see Footnote 2
on page 2.
1 ok = o p e n _ s e r i a l ( 1 , 2 , 1 1 5 2 0 0 ) / /COM p o r t i s 2 and baud r a t e i s 1 1 5 2 0 0
2 i f ok ~= 0 , e r r o r ( ’ S e r i a l p o r t i s not a c c e s i b l e ’ ) ; end
3 cmd_dcmotor_setup ( 1 , 3 , 1 , 9 , 1 0 ) / / S e t u p DC m o t o r o f t y p e 3 ( L293D ) ,
motor 1 , p i n s 9 and 1 0
4 for i = 1 : 4
5 cmd_dcmotor_run ( 1 , 1 , 1 0 0 ) / / M o t o r 1 r u n s a t PWM 1 0 0
6 sleep (3000) // f o r 3 s e c o n d s
7 cmd_dcmotor_run ( 1 , 1 , 0 ) // H a l t t h e motor
8 sleep (2000) // f o r 2 s e c o n d s
9 cmd_dcmotor_run ( 1 , 1 , −100) / / Run i t a t PWM 1 0 0 i n r e v e r s e
direction
10 sleep (2000) // for 2 seconds
11 end
12 cmd_dcmotor_release ( 1 , 1 ) // Motor 1 i s released
13 close_serial (1) ;

10.4 Controlling the DC motor from Xcos


In this section, we will see how to drive the DC motor from Scilab Xcos. We will carry
out the same three experiments as in the previous sections. For each experiment, we
will give the location of the zcos file and the parameters to set. The reader should
go through the instructions given in Sec. 3.3 before getting started.

1. First we will see a simple code that drives the DC motor for a specified time.
When the file required for this experiment is invoked, one gets the GUI as in
Fig. 10.5. In the caption of this figure, one can see where to locate the file.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 10.2. In case
of DCMOTOR_SB, enter 3 to indicate for L293D board. After clicking on OK,
another dialog box will pop up. In that, enter the PWM pin numbers as 9 and
10 and click OK. All other parameters are to be left unchanged.

2. Next, we will describe the Xcos code that drives the DC motor in both forward
and reverse directions. When the file required for this experiment is invoked,
134 10. Interfacing a DC Motor

Figure 10.5: Control of DC motor for a specified time from Xcos. This is what
one sees when Origin/user-code/dcmotor/scilab/dcmotor-clock.zco
s, see Footnote 2 on page 2, is invoked.

Table 10.2: Xcos parameters to drive the DC motor for a specified time

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
DCMOTOR_SB Type of Shield 3
Arduino card number 1
PWM pin numbers 9 10
Motor number 1
STEP_FUNCTION Step time 5
Initial Value 100
Final Value 0

one gets the GUI as in Fig. 10.6. In the caption of this figure, one can see
where to locate the file.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 10.3. All other
parameters are to be left unchanged.

3. Next, we will describe the Xcos code that drives the DC motor in a loop.
10.4. Controlling the DC motor from Xcos 135

Figure 10.6: Xcos control of the DC motor in forward and reverse directions. This
is what one sees when Origin/user-code/dcmotor/scilab/dcmotor-both
.zcos, see Footnote 2 on page 2, is invoked.

Table 10.3: Xcos parameters to drive the DC motor in forward and reverse directions

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
DCMOTOR_SB Type of Shield 3
Arduino card number 1
PWM pin numbers 9 10
Motor number 1
STEP_FUNCTION Step time 5
Initial Value 100
final value 0
CLOCK_c Period 1
Initialisation Time 0.1

When the file required for this experiment is invoked, one gets the GUI as in
Fig. 10.7. In the caption of this figure, one can see where to locate the file.
We will next explain how to set the parameters for this simulation. To set value
on any block, one needs to right click and open the Block Parameters or
double click. The values for each block is tabulated in Table 10.4. All other
136 10. Interfacing a DC Motor

Figure 10.7: Xcos control of the DC motor in both directions in a loop. This is what
one sees when Origin/user-code/dcmotor/scilab/dcmotor-loop.zcos,
see Footnote 2 on page 2, is invoked.

parameters are to be left unchanged.

Exercise 10.3 Carry out the following exercise:

1. Keep reducing the PWM value and find out the minimum value required to
run the DC motor. Is this value in agreement with what we found in the
previous section?
2. Change the PWM value to −100 and check if the DC motor rotates in the
opposite direction.
3. Find out the smallest PWM value required to make the motor run in the
opposite direction. That is, find the least count for both directions.
4. Come up with a method to rotate the motor in two directions for different
time periods.
10.4. Controlling the DC motor from Xcos 137

Table 10.4: Xcos parameters to drive the DC motor in a loop

Name of the block Parameter name Value


ARDUINO_SETUP Identifier of Arduino Card 1
Serial com port number 2, see Footnote 4 on page 32
TIME_SAMPLE Duration of acquisition(s) 10
Sampling period(s) 0.1
DCMOTOR_SB Type of Shield 3
Arduino card number 1
PWM pin numbers 9 10
Motor number 1
STEP_FUNCTION 1 Step time 3
Initial Value 100
Final Value 0
STEP_FUNCTION 2 Step time 5
Initial Value 0
Final Value 100
STEP_FUNCTION 3 Step time 7
Initial Value 0
Final Value 100
BIGSOM_f Inputs ports signs/gain [1;-1;1]
138 10. Interfacing a DC Motor
Chapter 11

Implementation of Modbus
Protocol

In the previous chapters, we have discussed the programs to experiment with the
sensors and actuators that come with the shield, a DC motor, and a servomotor. One
may categorize these programs as either basic or intermediate. In this chapter, we
will learn one of the advanced applications that can be built using the toolbox. Recall
the FLOSS discussed in the book, by default, does not have the capability to connect
to Arduino. All such add-on functionalities are added to the FLOSS using toolboxes.
Beginners might want to skip this chapter in the first reading. This experiment
enables interfacing Modbus-based devices with the FLOSS-Arduino toolbox. This
functionality has a wide number of applications in the industrial sector.

11.1 Preliminaries
Modbus is an open serial communication protocol developed and published by Mod-
icon in 1979 [18] [19]. Because of ease of deployment and maintenance, it finds
wide applications in industries. The Modbus protocol provides a means to transmit
information over serial lines between several electronic devices to control and mon-
itor them. The controlling device requests for reading or writing information and
is known as the Modbus master/client. On the other hand, the device supplying
the information is called Modbus slave/server. All the slaves/servers have a unique
id and address. Typically, there is one master and a maximum of 247 slaves [20].
Fig. 11.1 shows a representation of Modbus protocol.
During the communication on a Modbus network, the protocol determines how
the controller gets to know its device address, recognizes the the message provided
and decides the action to be taken, and accordingly extracts data and information
140 11. Implementation of Modbus Protocol

Figure 11.1: Block diagram representation of the Protocol

Figure 11.2: Cycle of query-response between master and slave

contained in the message. A typical structure of the communication protocol is


shown in Fig. 11.2. The data is sent as a series of zeros and ones, i.e., bits wherein
zeros are sent as positive voltages and ones as negative.
Different versions of Modbus protocol exist on serial lines, namely Modbus RTU,
ASCII, and TCP [20]. The energy meter used in this chapter supports the Modbus
RTU protocol. In Modbus RTU, the data is coded in binary and requires only one
communication byte. This is ideal for use over RS232 or RS485 networks at baud
rates between 1200 and 115K.
RS485 is one of the most widely used bus standards for industrial applications.
It uses differential communication lines to communicate over long distances and
requires a dedicated pair of signal lines, say A and B, to exchange information.
11.1. Preliminaries 141

Table 11.1: Pins available on RS485 and their usage

Pin name Usage


Vcc 5V
B Inverting receiver input
A Non-inverting receiver input
GND Ground (0V)
RO Receiver output
RE Receiver enable
DE Data enable
DI Data input

Figure 11.3: Pins in RS485 module

Here, the voltage on one line equals to the inverse of the voltage on the other line.
In other words, the output is 1, if A - B > 200mV, and 0, if B - A > 200mV.
Fig. 11.3 shows the pins available on a typical RS485 module. As shown in Fig. 11.3,
there are four pins on each side of the module. Table 11.1 summarizes the usage of
these pins.

11.1.1 Energy meter


An energy meter is a device that measures the amount of electricity consumed by the
load. This book makes use of the EM6400 series energy meter. It is a multifunction
digital power meter by Schneider Electric. It reads various parameters such as phase
voltage, current, active power, reactive power, power factor, etc. Before using the
meter, one has to program system configuration, PT, CT ratios, communication
142 11. Implementation of Modbus Protocol

Table 11.2: Operations supported by Modbus RTU

Function Code Action Table Name


01 (01 hex) Read Discrete Output Coils
05 (05 hex) Write single Discrete Output Coil
15 (0F hex) Write multiple Discrete Output Coils
02 (02 hex) Read Discrete Input Contacts
04 (04 hex) Read Analog Input Registers
03 (03 hex) Read Analog Output Holding Registers
06 (06 hex) Write single Analog Output Holding Register
16 (10 hex) Write multiple Analog Output Holding Registers

Table 11.3: Individual parameter address in EM6400

Parameter Description Address


V1 Voltage phase 1 to neutral 3927
A1 Current, phase 1 3929
W1 Active power, phase 1 3919

parameters through front panel keys. The reason behind using this energy meter is
the fact that it supports the Modbus RTU protocol for communication.
Multiple operations can be performed with devices supporting Modbus. Every
operation has its own fixed function code (coil status - 01, input status - 02, holding
registers - 03, input registers - 04, etc.), which is independent of devices. The function
code tells the slave which table to access and whether to read from or write to the
table. All the parameter values are stored in the output holding registers. Different
holding registers hold the values of different parameters. Table 11.2 summarizes
the various operations which Modbus RTU supports. One can locate the addresses
of individual parameters in the user manual for EM6400. Table 11.3 provides the
addresses for three individual parameters, which will be accessed in this chapter.
In Modbus protocol, the master needs to send a request packet (referred as RQ
hereafter) to the slave to read any of the slave’s parameters. When the slave receives
an RQ, it needs to come up with a response packet (referred as RP hereafter), which
contains the value requested by the master. In other words, an RQ is a message from
the master to a slave and an RP is a message from the slave back to the master. We
will first explain the structure of an RQ, followed by an example. An RQ consists of
the following fields:

1. Slave id: The first byte of every Modbus message is a slave id. The master
specifies the id of the slave to which the request message is addressed. Slaves
11.1. Preliminaries 143

Table 11.4: A request packet to access V1 in EM6400

Field of the RQ Value for reading V1


Slave id 01
Function code 03
Address of the register 3926 (hex value = 0F56)
Number of registers 02
CRC bytes 270F

must specify their own id in every response message (RP).


2. Function code: The second byte of every Modbus message is a function code.
This code determines the type of operation to be performed by the slave.
Table 11.2 enlists the various function codes.
3. Address of the register: After the above two bytes, RQ specifies the data
address of the first register requested.
4. Number of registers: This field denotes the total number of registers requested.
5. CRC bytes: The last two bytes of every Modbus message are CRC bytes. CRC
stands for Cyclic Redundancy check. It is added to the end of every Modbus
message for error detection. Every byte in the message is used to calculate
the CRC. The receiving device also calculates the CRC and compares it to
the CRC from the sending device. If even one bit in the message is received
incorrectly, the CRCs will be different, resulting in an error.

Note: There are some online tools [21] by which one can calculate the CRC
bytes. However, one should note that the calculated CRC bytes should be men-
tioned in little-endian format, which means that the first register contains the
least significant bit (LSB) and the next register contains the most significant
bit (MSB).
Let us say, we want to access V1 (Voltage phase 1 to neutral) in the energy meter.
From Table 11.3, it may be noted that the address of V1 is 3927. The size of each
Modbus register is 16 bits and all EM6400 readings are of 32 bits. So, each reading
occupies two consecutive Modbus registers. Thus, we need to access two consective
holding registers (starting from 3926) to get V1. Table 11.4 summarizes the values
for the various fields in the RQ required to read/access V1. Now, we explain the
structure of an RP, followed by an example. An RP consists of following fields:
1. Slave id: In an RP, the slaves must specify their own id.
144 11. Implementation of Modbus Protocol

Table 11.5: A response packet to access V1 in EM6400

Field of the RP Value for reading V1


Slave id 01
Function code 03
Number of data bytes to follow 04
Data in the first requested register 2921
Data in the second requested register 4373
CRC bytes D2B0

2. Function code: Like the RQ, the second byte of RP is the function code. This
code determines the type of operation to be performed by the slave. Table 11.2
enlists the various function codes.

3. Number of data bytes to follow: It refers to the total number of bytes read.
As our RQ has 2 registers each of two bytes, we expect a total of 4 bytes.

4. Data in the first requested register: It refers to the data stored in the first
register.

5. Data in the second requested register: It refers to the data stored in the second
register.

6. CRC bytes: As stated earlier, the last two bytes of every Modbus message
are CRC bytes. Like RQ, the receiving device also calculates the CRC and
compares it to the CRC from the sending device.
Let us consider the RP, which we have received as a response to the RQ mentioned
in Table 11.4. Table 11.5 summarizes the values for the various fields in this RP.
In this RP, we consider the data in the two requested registers to be 43732921 in
hexadecimal. The reason behind keeping the data in the second requested register
as the MSB is that the obtained values are being read in little-endian format. After
converting this value to floating point using the IEEE Standard for Floating-Point
Arithmetic (IEEE 754), we obtain the value as 243.16. Thus, the value of V1 (Voltage
phase 1 to neutral) in the energy meter is found to be 243.16 Volts.

11.1.2 Endianness
Most of the numeric values to be stored in the computer are more than one byte long.
Thus, there arises a question of how to store the multibyte values on the computer
machines where each byte has its own address i.e., which byte gets stored at the
“first” (lower) memory location and which bytes follow in higher memory locations.
11.1. Preliminaries 145

Table 11.6: Memory storage of a four-byte integer in little-endian and big-endian

Memory Address Byte Little-endian Big-endian


3900 8A43 MSB LSB
3901 436B LSB MSB

For example, let us picture this. A two-byte integer 0x5E5F is stored on the disk
by one machine, with the 0x5E (MSB) stored at the lower memory address and the
0x5F (LSB) stored at a higher memory address. But there is a different machine
that reads this integer by picking 0x5F for the MSB and 0x5E for the LSB, giving
0x5F5E. Hence, it results in a disagreement on the value of the integer between the
two machines. However, there is no so-called “right” ordering to store the bytes in
the case of multibyte quantities. Hardware is built to store the bytes in a particular
fashion, and as long as compatible hardware reads the bytes in the same fashion,
things are fine. Following are the two major types of storing the bytes:

1. Little-endian: If the hardware is designed so that the LSB of a multibyte


integer is stored “first”at the lowest memory address, then the hardware is said
to be little-endian. In this format, the ”little” end of the integer gets stored
first and the next bytes are stored in higher (increasing) memory locations.

2. Big-endian: Here, the hardware is designed so that the MSB of a multibyte


integer is stored “first”at the lowest memory address. Thus, the “big” end of
the integer gets stored first and accordingly the next bytes get stored in higher
(increasing) memory locations.

For example, let us take a four-byte integer 0x436B84A3. Considering that the read
holding registers in Modbus protocol are 16-bits each, the LSB (or the little end) of
this integer is 0x84A3, and the MSB (or the big end) of this integer is 0x436B. Then,
the memory storage patterns for the integer would be like that shown in Table 11.6.

To represent the hexadecimal values of the read holding registers into user friendly
decimal (floating point) values, we follow IEEE 754 standard. Most common stan-
dards for representing floating point numbers are:

1. Single precision: In this standard, 32 bits are used to represent a floating-point


number. Out of these 32 bits, one bit is for the sign bit, 8 bits for the exponent,
and the remaining 23 bits for mantissa.

2. Double precision: Here, 64 bits are used to represent a floating-point number.


Out of these 64 bits, one bit represents the sign bit, 11 bits for the exponent,
146 11. Implementation of Modbus Protocol

Figure 11.4: Block diagram for reading the parameters in energy meter

and the remaining 52 bits for mantissa. As the name indicates, this standard
is used where precision matters more.

There are several online converters [22] which peform the IEEE 754 floating point
conversion. In this chapter, a function has been formulated for this conversion,
wherever needed.

11.2 Setup for the experiment


This section discusses the setup for configuring Arduino Uno as Modbus master and
energy meter as the slave. The block diagram is shown in Fig. 11.4 , whereas Fig. 11.5
presents the actual setup. The following steps discuss the various connections of this
setup:

1. Arduino Uno has only one serial port. It communicates on the digital pins 0
and 1 as well as on the computer via USB. Since we want serial communication
which shouldn’t be disturbed by the USB port and the Serial Monitor, we use
the Software Serial library. Using this library, we can assign any digital pins
as RX and TX and use it for serial communication. In this experiment, pin
10 (used as RX) and pin 11 (used as TX) are connected to RO (Receive Out)
and DI (Data In) pins of the RS485 module respectively.

2. DE (Data Enable) and RE (Receive Enable) pins of RS 485 are shorted and
connected to digital pin 3 of the Arduino Uno board. This serves as a control
pin that will control when to receive and transmit serially.
11.3. Software required for this experiment 147

Figure 11.5: Experimental set up for reading energy meter

3. Vcc and GND of the RS485 module are connected to Vcc and GND of the
Arduino Uno board.

4. A and B pins of RS485 module are connected to A (Pin 7) and B (Pin 14) pins
of the energy meter. These two pins of the energy meter are meant for RS485
communication.

5. A 120kΩ termination resistor is connected between pins A and B to avoid


reflection losses in the transmission line.

11.3 Software required for this experiment


Apart from the FLOSS-Arduino toolbox, the software for this experiment comprises
two parts:

1. Firmware for Arduino Uno: This firmware is needed to communicate with the
FLOSS (using serial interface), and with RS485 module (using Software Serial
interface). Control logic to enable receive and transmit modes of MAX485 chip
is also present in this firmware. Fig. 11.6 demonstrates the overall implemen-
tation of this firmware. The firmware is provided in Sec. 11.3.1.

2. FLOSS code: This code requests the parameters in the energy meter by sending
an RQ to Arduino Uno from the FLOSS. Then it waits till an RP is available
148 11. Implementation of Modbus Protocol

Figure 11.6: Flowchart of Arduino firmware

from the Arduino Uno. After receiving the RP, it extracts the data from
this packet and converts it into IEEE 754 floating-point format. The overall
implementation is being described below:
11.4. Manifestation of Modbus protocol through Scilab 149

(a) Frame an RQ to be sent to the energy meter (slave) in ASCII coded


decimal format.
(b) Send the RQ serially to Arduino Uno.
(c) Let Arduino Uno send the RQ to the energy meter via RS485 module.
(d) Let the energy meter send the RP to Arduino Uno via RS485 module.
(e) Read the RP available on Arduino Uno.
(f) Extract the data stored in holding registers from the RP.
(g) Assuming this data to be stored in little-endian format, convert this data
in floating-point values using IEEE 754 standard.
(h) Display the value in the Console, output window, Command Prompt (on
Windows) or Terminal (on Linux), as the case maybe.
Fig. 11.7 presents the sequence in which the steps mentioned above are exe-
cuted.

11.3.1 Arduino Firmware


Arduino Code 11.1 First 10 lines of the firmware for Modbus. Available at Orig
in/user-code/modbus/arduino, see Footnote 2 on page 2.
1 /∗ . . . . . . . . . . . . . . . . . . . . . . . . c r c f u n c t i o n . . . . . . . . . . . . . . . . . . . . . . . ∗/
2
3 s t a t i c unsigned char auchCRCHi [ ] = {0 x00 , 0xC1 , 0 x81 , 0 x40 , 0 x01 , 0xC0 ,
0 x80 , 0 x41 , 0 x01 , 0xC0 , 0 x80 , 0 x41 , 0 x00 , 0xC1 , 0 x81 ,
4 0 x40 , 0 x01 , 0xC0 , 0 x80 , 0 x41 , 0 x00 , 0xC1 , 0 x81 , 0 x40 , 0 x00 , 0xC1 , 0 x81 ,
0 x40 , 0 x01 , 0xC0 ,
5 0 x80 , 0 x41 , 0 x01 , 0xC0 , 0 x80 , 0 x41 , 0 x00 , 0xC1 , 0 x81 , 0 x40 , 0 x00 , 0xC1 ,
0 x81 , 0 x40 , 0 x01 ,
6 0xC0 , 0 x80 , 0 x41 , 0 x00 , 0xC1 , 0 x81 , 0 x40 , 0 x01 , 0xC0 , 0 x80 , 0 x41 , 0 x01 ,
0xC0 , 0 x80 , 0 x41 ,
7 0 x00 , 0xC1 , 0 x81 , 0 x40 , 0 x01 , 0xC0 , 0 x80 , 0 x41 , 0 x00 , 0xC1 , 0 x81 , 0 x40 ,
0 x00 , 0xC1 , 0 x81 ,
8 0 x40 , 0 x01 , 0xC0 , 0 x80 , 0 x41 , 0 x00 , 0xC1 , 0 x81 , 0 x40 , 0 x01 , 0xC0 , 0 x80 ,
0 x41 , 0 x01 , 0xC0 ,
9 0 x80 , 0 x41 , 0 x00 , 0xC1 , 0 x81 , 0 x40 , 0 x00 , 0xC1 , 0 x81 , 0 x40 , 0 x01 , 0xC0 ,
0 x80 , 0 x41 , 0 x01 ,
10 0xC0 , 0 x80 , 0 x41 , 0 x00 , 0xC1 , 0 x81 , 0 x40 , 0 x01 , 0xC0 , 0 x80 , 0 x41 , 0 x00 ,
0xC1 , 0 x81 , 0 x40 ,

11.4 Manifestation of Modbus protocol through Scilab


The objective of this experiment is to make the user acquainted with the demonstra-
tion of Modbus protocol through the Scilab-Arduino toolbox. It gives an insight into
150 11. Implementation of Modbus Protocol

Figure 11.7: Flowchart of the steps happening in the FLOSS code

how to acquire readings from the energy meter and interpret them accordingly. As
explained in Sec. 11.1.1, an energy meter is a device that gives us different electrical
parameters, including voltage, current, and power, consumed by a device. Here, we
aim to obtain these values using the Scilab-Arduino toolbox. For data transmission,
we have used an RS485 module.
Scilab is used for giving the required parameters to Arduino Uno. For example,
the user will tell the required slave address to be accessed and the number of registers
to be read from or written to. Here, Arduino Uno acts as a master and energy meter
as a slave. Therefore, referring to a particular slave address will refer to the registers
that hold the desired electrical parameters (current, voltage, power, etc.), which we
11.5. Reading the electrical parameters from Scilab 151

want to read from the energy meter.


In this experiment, Arduino Uno is connected to the energy meter via an RS485
module which facilitates long-distance communication. Scilab sends the RQ to the
Arduino Uno which in turn sends it to the energy meter. The energy meter then
accesses the values in the required addresses in its memory and transfers them back.
This again is in the form of another packet called RP. In this packet, the data is
stored in a little-endian hexadecimal format. Thus, we make use of IEEE 754 to
obtain the decimal value from this data.

11.5 Reading the electrical parameters from Scilab


11.5.1 Reading the electrical parameters
In this section, we will show how to access the three parameters (voltage, current,
and active power) in the energy meter. As discussed above, we will send an RQ
from Scilab to Arduino Uno. Subsequently, Arduino Uno will provide us with an
RP, which can be decoded to extract the desired parameter. The reader should go
through the instructions given in Sec. 3.2 before getting started.

11.5.2 Scilab Code


Scilab Code 11.1 First 10 lines of the Scifunc block function. Available at Origi
n/user-code/modbus/scilab, see Footnote 2 on page 2.
1
2 // v o l t a g e
3 f u n c t i o n p=read_val ( addr_byte )
4 h=o p e n _ s e r i a l ( 1 , 2 , 9 6 0 0 )
5
6 // f o r x =1:5
7 / / a r r =[ a s c i i ( 0 1 ) a s c i i ( 0 3 ) a s c i i (15) a s c i i (86) a s c i i (00) a s c i i (02)
a s c i i (39) a s c i i (15) ] ;
8 // a r r 1= s t r i n g ( a r r )
9 i f ( addr_byte==86)
10 a r r a y 1=a s c i i ( 0 1 )+ a s c i i ( 0 3 ) + a s c i i ( 1 5 ) + a s c i i ( 8 6 ) + a s c i i ( 0 0 ) +
a s c i i (02) + a s c i i (39) + a s c i i (15)

Scilab Code 11.2 First 10 lines of the code for single phase current output. Avail-
able at Origin/user-code/modbus/scilab, see Footnote 2 on page 2.
1 // c u r r e n t
2 // f u n c t i o n read_current ()
3 function read_current ( )
4
152 11. Implementation of Modbus Protocol

5 h=o p e n _ s e r i a l ( 1 , 2 , 9 6 0 0 )
6 // f o r x =1:5
7 a r r =[ a s c i i ( 0 1 ) a s c i i ( 0 3 ) a s c i i ( 1 5 ) a s c i i ( 8 8 ) a s c i i ( 0 0 ) a s c i i ( 0 2 )
a s c i i (70) a s c i i (204) ] ;
8
9 a r r 1=a s c i i ( 0 1 ) + a s c i i ( 0 3 ) + a s c i i ( 1 5 ) + a s c i i ( 8 8 ) + a s c i i ( 0 0 ) +
a s c i i (02) + a s c i i (70) + a s c i i (204) ;
10 w r i t e _ s e r i a l (1 , arr1 , 8) ;

Scilab Code 11.3 First 10 lines of the code for single phase voltage output. Avail-
able at Origin/user-code/modbus/scilab, see Footnote 2 on page 2.
1 // v o l t a g e
2 function read_voltage ( )
3 // e n d f u n c t i o n
4 h=o p e n _ s e r i a l ( 1 , 2 , 9 6 0 0 )
5
6 // f o r x =1:5
7 a r r =[ a s c i i ( 0 1 ) a s c i i ( 0 3 ) a s c i i ( 1 5 ) a s c i i ( 8 6 ) a s c i i ( 0 0 ) a s c i i ( 0 2 )
a s c i i (39) a s c i i (15) ] ;
8 // a r r 1= s t r i n g ( a r r )
9 aac=a s c i i ( 0 1 )+ a s c i i ( 0 3 ) + a s c i i ( 1 5 ) + a s c i i ( 8 6 ) + a s c i i ( 0 0 ) +
a s c i i (02) + a s c i i (39) + a s c i i (15)
10 w r i t e _ s e r i a l ( 1 , aac , 8 ) ;

Scilab Code 11.4 First 10 lines of the code for single phase active power output.
Available at Origin/user-code/modbus/scilab, see Footnote 2 on page 2.
1 // e n e r g y
2 f u n c t i o n read_active_power ( )
3
4 h=o p e n _ s e r i a l ( 1 , 2 , 9 6 0 0 )
5 // f o r x =1:5
6 a r r =[ a s c i i ( 0 1 ) a s c i i ( 0 3 ) a s c i i ( 1 5 ) a s c i i ( 7 8 ) a s c i i ( 0 0 ) a s c i i ( 0 2 )
a s c i i (167) a s c i i (08) ] ;
7 a s c 1=a s c i i ( 0 1 ) + a s c i i ( 0 3 ) + a s c i i ( 1 5 ) + a s c i i ( 7 8 ) + a s c i i ( 0 0 ) +
a s c i i (02) + a s c i i (167) + a s c i i (08) ;
8
9 w r i t e _ s e r i a l ( 1 , asc1 , 8 ) ;

Note: After we send the RQ from Scilab to the energy meter, we will receive
an RP from the energy meter. RP contains the data requested. This data is read
serially in Scilab and the bytes so received are stored in a variable. On analyzing the
bytes received, we observe some blank spaces received along with the data. So the
required data starts from the fourth byte available, excluding spaces. For example, If
there are n spaces received before the packet, so the required data would be available
11.5. Reading the electrical parameters from Scilab 153

Figure 11.8: Single phase current output on Scilab Console

from (n+4)th position onwards. It means that we have to analyze the four bytes
starting at (n+4)th position. Note that the RP may have one or more spaces at the
start or the end. That’s why we may have to shift our index to extract the desired
data.

11.5.3 Output in the Scilab Console

In this section, we present the results. In this experiment, the three parameters:
voltage, current, and active power in the energy meter have been accessed and dis-
played on the Scilab console. For each of these three parameters, we present two
image: one showing the reading being shown in the energy meter and the another
showing the value being displayed in the Scilab Console.

1. Single phase current output: Fig. 11.8 and Fig. 11.9 show Scilab code output of
current in Amperes and corresponding snapshot of energy meter display with
a single load rated 60W-230V.

2. Single phase voltage output: Fig. 11.10 and Fig. 11.11 show Scilab code output
of voltage in Volts and corresponding snapshot of energy meter display with a
single load rated 60W-230V.

3. Single phase active power output: Fig. 11.12 and Fig. 11.13 show Scilab code
output of active power in Watts and corresponding snapshot of energy meter
display with a single load rated 60W-230V.
154 11. Implementation of Modbus Protocol

Figure 11.9: Single phase current output in energy meter

Figure 11.10: Single phase voltage output on Scilab Console

11.6 Reading the electrical parameters from Xcos


In this section we will carry out the same experiments discussed in the previous
sections but through Xcos. One should go through Sec. 3.3 before continuing.

1. The Xcos diagram for performing the read values for single phase current, single
phase voltage and single phase power operation is as shown in Fig. 11.14. The
location of the xcos file is mentioned in the caption of the figure.
11.6. Reading the electrical parameters from Xcos 155

Figure 11.11: Single phase voltage output in energy meter

Figure 11.12: Single phase active power output on Scilab Console

The parameters of the blocks can be changed by right clicking on the block
and choosing Block Parameters. One can also double click on the block.
The values for each block is tabulated in Table 11.7. All other parameters are
156 11. Implementation of Modbus Protocol

Figure 11.13: Single phase active power output in energy meter

Figure 11.14: Xcos diagram to read energy meter values. This is what one
sees when Origin/user-code/modbus/scilab, see Footnote 2 on
page 2read_value_xcos.zcos is invoked.

to be left unchanged.
11.6. Reading the electrical parameters from Xcos 157

Table 11.7: Xcos parameters to read energy meter values

Name of the block Parameter name Value


CONST_m Address byte for voltage 86
Address byte for current 88
Address byte for power 78
SELF_SWITCH Signal Routing on/off
BIGSOM_f Scalar vector addition/subtraction Summation [1;1;1]
scifunc_block_m Block for userdefined function read_value.sci
AFFICH_m Block inherits(1) or not (0) 0
CLOCK_c Period 0.1
Initialisation Time 0
158 11. Implementation of Modbus Protocol
Appendix A

Procuring the Hardware

One may need some or all of the components listed below to carry out the experiments
explained in the book:

1. Arduino Uno

2. Components required to build the shield

3. External actuators that work with the shield

4. Components required for the breadboard based experiments

We now provide an approximate cost of the above parts, mainly to keep a beginner
informed, see Table A.1. Because of the fluctuations in exchange rates, and the
availability issues, pricing could change considerably.

Table A.1: Approximate cost of the components

Item Cost (|)


Arduino Uno 675
Components for the shield, 350
given in Table 2.2
External actuators (motor, 400
motor driver, servo motor) to
work with the shield
Half breadboard 250
Components that go with the 700
breadboard

159
160 A. Procuring the Hardware

With the components and the Gerber file mentioned in Sec. 2.4, it should be
possible to create the PCB, and solder the components, so as to arrive at the shield,
as shown in Fig. 2.12. This is the least expensive option.
The readymade shield is also available on E-commerce websites like Amazon [23]
and Flipkart [24], in the name of Ecolight® Sensor Shield V-1.2 Compatible with
Arduino Uno R3.
Interested people may contact [email protected] or at +91 22 2576 4133.
References

[1] T. Martin. Use of scilab for space mission analysis.


https://www.scilab.org/community/scilabtec/2009/Use-of-Scilab-for-space-
mission-analysis. Seen on 28 June 2015.

[2] B. Jofret. Scilab arduino toolbox. http://atoms.scilab.org/. Seen on 28 June


2015.

[3] oshwa.org. http://www.oshwa.org/definition. Seen on 28 June 2015.

[4] Mateo Zlatar. Open source hardware logo. http://www.oshwa.org/open-source-


hardware-logo. Seen on 28 June 2015.

[5] Arduino uno. https://www.arduino.cc/en/uploads/Main/ArduinoUnoFront240.jpg.


Seen on 28 June 2015.

[6] Arduino mega. https://www.arduino.cc/en/uploads/Main/ArduinoMega2560_R3


_Fronte.jpg. Seen on 28 June 2015.

[7] Lilypod arduino. https://www.arduino.cc/en/uploads/Main/LilyPad_5.jpg.


Seen on 28 June 2015.

[8] Arduino phone. http://www.instructables.com/id/ArduinoPhone/. Seen on 28


June 2015.

[9] Candy sorting machine. http://beta.ivc.no/wiki/index.php/Skittles_M%26M%27s


_Sorting_Machine. Seen on 28 June 2015.

[10] 3d printer. http://www.instructables.com/id/Arduino-Controlled-CNC-3D-


Printer/. Seen on 28 June 2015.

[11] Shield. http://codeshield.diyode.com/about/schematics/. Seen on 28 June


2015.

[12] scilab.org. http://www.scilab.org/scilab/about. Seen on 28 June 2015.

161
162 References

[13] scilab.org. http://www.scilab.org/scilab/interoperability. Seen on 28 June 2015.

[14] scilab.org. http://www.scilab.org/scilab/features/xcos. Seen on 28 June 2015.

[15] Thermistor - wikipedia. https://en.wikipedia.org/wiki/Thermistor. Seen on 2


May 2021.

[16] Secrets of arduino pwm. https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM.


Seen on 5 May 2021.

[17] Servo. https://www.arduino.cc/reference/en/libraries/servo/. Seen on 6 May


2021.

[18] Modbus. https://modbus.org/. Seen on 6 May 2021.

[19] Paavni Shukla, Sonal Singh, Tanmayee Joshi, Sudhakar Kumar, Samrudha
Kelkar, Manas R. Das, and Kannan M. Moudgalya. Design and development of
a modbus automation system for industrial applications. In 2017 6th Interna-
tional Conference on Computer Applications In Electrical Engineering-Recent
Advances (CERA), pages 515–520, 2017.

[20] Simply modbus. https://simplymodbus.ca/. Seen on 6 May 2021.

[21] Online crc. https://www.lammertbies.nl/comm/info/crc-calculation. Seen on 2


May 2021.

[22] Floating point converter. https://www.h-


schmidt.net/FloatConverter/IEEE754.html. Seen on 6 May 2021.

[23] Ecolight® sensor shield v-1.2 compatible with arduino uno r3.
https://www.amazon.in/dp/B09G8BWDDD/. Seen on 8 Jan 2022.

[24] Ecolight sensor shield v-1.2 compatible with arduino uno educational electronic
hobby kit. https://www.flipkart.com/ecolight-sensor-shield-v-1-2-compatible-
arduino-uno-educational-electronic-hobby-kit/p/itm73d12ca9ae129. Seen on 8
Jan 2022.

You might also like