Scilab
Scilab
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
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
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
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
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
Kannan Moudgalya
IIT Bombay
2 October 2022
List of Figures
ix
x List of Figures
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
xiii
xiv List of Tables
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
11.1 First 10 lines of the firmware for Modbus Energy Meter experiment 149
xv
xvi List of Arduino Code
List of Scilab Code
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
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
xix
xx List of Acronyms
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
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).
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.
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.
2. Beagle board, Panda board, OLinuXino are ARM based development boards.
8 2. Hardware Environment
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.
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.
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
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
Candy sorting machine: As the name suggests, this machine can sort candy
based on its color to separate jars [9].
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
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. Shield containing
2.6. Doing the Experiments with a Breadboard 13
(a) LED
(b) LDR
(c) Push Button
(d) Thermistor
4. Servomotor
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.
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
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
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.
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.
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.
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
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
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
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.
2. Upload: Compiles your code and uploads it to the Arduino I/O board
4. Open: Presents a menu of all the sketches in your sketchbook - clicking one
will open it within the current window
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
2. Sketch
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
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.
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.
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.
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
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.
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
- 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 .
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
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.
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.
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
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.
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
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
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
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.2: Internal connection diagram for the RGB LED on the shield
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.
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.
Before that, we need to define pin 9 as the output pin. This is achieved by the
command,
1 pinMode ( 9 , OUTPUT) ;
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) ;
// 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
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 }
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 ) ;
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
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.
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
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.
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
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
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
The values for each block required in this program are tabulated in Table 4.4.
All other parameters are to be left unchanged.
Interfacing a Pushbutton
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.
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
Figure 5.3: A pushbutton to control an LED with Arduino Uno using a breadboard
is connected to the rightmost leg of the RGB LED. Rest of the connections are same
as that in Fig. 5.2.
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.
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.
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 }
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
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.
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) ;
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
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
double click. The values for each block is tabulated in Table 5.2. All other
parameters are to be left unchanged.
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
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
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.
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
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.
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
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 }
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.
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) ;
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.
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
Interfacing a Potentiometer
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.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.
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) ;
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 }
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.
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.
Table 7.1: Xcos parameters to turn on different LEDs depending on the potentiome-
ter value
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
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
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
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.
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
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.
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.
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.
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
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.
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.
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) ;
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.
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.
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.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.
Table 8.2: Xcos parameters to read thermistor and switch the buzzer
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
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.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>
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
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.
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.
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?
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
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 }
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
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.
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
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
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)
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.
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
Table 9.5: Parameters to rotate the servomotor based on the input from the poten-
tiometer
Interfacing a DC Motor
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
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.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) ;
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) ; //
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.
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.
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
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 }
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 )
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) ;
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
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.
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) ;
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
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
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.
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
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
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.
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
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
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
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:
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:
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.
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
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.
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
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
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
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
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.
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
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
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.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
One may need some or all of the components listed below to carry out the experiments
explained in the book:
1. Arduino Uno
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.
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
161
162 References
[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.
[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.