Microcontroller
IEECT 4
Introduction to Microcontroller
• A microcontroller (MC, UC, or μC) or
microcontroller unit (MCU) is a small
computer on a single integrated circuit.
• A microcontroller contains one or more
CPUs (processor cores) along with
memory and programmable input/output
peripherals.
Introduction to Microcontroller
• A microcontroller is a compact integrated circuit
designed to govern a specific operation in an
embedded system.
• A typical microcontroller includes a processor,
memory and input/output (I/O) peripherals on a
single chip.
• A microcontroller is an electronic device belonging
to the microcomputer family.
• These are fabricated using the VLSI (Very Large
Scale Integration) technology on a single chip.
Introduction to Microcontroller
• Microcontroller is also known as “Computer-on-a-Chip”.
• It is named so, because not only the CPU, but RAM, ROM,
I/O ports, Timer/Counter, Serial I/Os all are put together
on a single microcontroller chip.
• A microcontroller also called an embedded controller
because the microcontroller and its support circuits are
often built into, or embedded in, the devices they
control.
• A microcontroller is available in different word lengths
like microprocessors (4bit, 8bit, 16bit, 32bit, 64bit and
128-bit microcontrollers are available today).
Block Diagram of Microcontroller
Memory
• Memory spaces such as RAM, ROM, EPROM or
EEPROM are there to store data and programs.
• For data storage, volatile memory RAM is used
while for the program and operating parameter
storage ROM and other memory spaces are used.
• A microcontroller usually has a certain amount of
RAM and ROM (EEPROM, EPROM, etc) or flash
memories for storing program source codes.
Timers/counters
• This is the one of the useful function of a microcontroller.
• A microcontroller may have more than one timer and
counters.
• The timers and counters provide all timing and counting
functions inside the microcontroller.
• The major operations of this section are performed clock
functions, modulations, pulse generations, frequency
measuring, making oscillations, etc.
• This also can be used for counting external pulses.
• There is a watchdog timer. A watchdog timer is a portion of
hardware that can be used to automatically detect software
anomalies/malfunctions and reset the processor if any occur
Parallel input/output ports
• Parallel input/output ports are mainly used to
drive/interface various devices such as LCD’S,
LED’S, printers, memories, etc to a
microcontroller.
Serial ports
• Serial ports provide various serial interfaces
between a microcontroller and other
peripherals like parallel ports.
Interrupt control
• The interrupt control used for providing
interrupt (delay) for a working program.
• The interrupt may be external (activated by
using interrupt pin) or internal (by using
interrupt instruction during programming).
Special functioning block
• Some microcontrollers used only for some
special applications (e.g. space systems and
robotics) these controllers containing
additional ports to perform such special
operations.
• This considered as special functioning block.
Analog to Digital Converter (ADC)
• ADC converters are used for converting the
analog signal to digital form.
• The input signal in this converter should be in
analog form (e.g. sensor output) and the
output from this unit is in digital form.
• The digital output can be used for various
digital applications (e.g. measurement
devices).
Digital to Analog Converter (DAC)
• DAC perform reversal operation of ADC
conversion. DAC converts the digital signal into
analog format.
• It usually used for controlling analog devices
like DC motors, various drives, etc.
Advantages of microcontroller
• The main advantages of microcontrollers are given.
• Microcontrollers act as a microcomputer without any
external digital parts.
• As the higher integration inside microcontroller reduces
cost and size of the system.
• Usage of a microcontroller is simple, easy to troubleshoot
and system maintaining.
• Most of the pins are programmable by the user for
performing different functions.
• Easily interface additional RAM, ROM, I/O ports.
• Low time required for performing operations.
Disadvantages of Microcontrollers
• Microcontrollers have got more complex
architecture than that of microprocessors.
• Microcontrollers are used for dedicated
application only.
• Only perform a limited number of executions
simultaneously.
• Mostly used in micro-equipment.
• Cannot interface high power devices directly.
Comparison between microprocessor and
microcontroller
Applications of microcontroller
1. Consumer Electronics Products: Toys, Cameras, Robots, Washing
Machine, Microwave Ovens etc. [any automatic home appliance]
2. Instrumentation and Process Control: Oscilloscopes, Multi-meter,
Leakage Current Tester, Data Acquisition and Control etc.
3. Medical Instruments: ECG machine, Electronic Cardiac Monitor, Blood
gas analyzer, Blood Glucose Monitor, MRI Machine etc.
4. Communication: Cell Phones, Telephone Sets, Answering Machines etc.
5. Office Equipment: Fax, Printers, etc.
6. Multimedia Application: Mp3 Player, PDAs, optical players, digital
camcorders etc.
7. Automobile: Speedometer, Auto-breaking system etc.
8. Robotics: Domestic or household robots, Industrial robots, Medical
robots, Service robots, Military robots, Entertainment robots, Space
robots,
Arduino Micro-controller
Arduino coding
What is Arduino
• Arduino IDE (Integrated Development
Environment) is an essential which makes the
task of uploading code on Arduino boards, an
easy task. Instead of writing them at the
assembly level, the IDEs make it convenient
and the codes are written in high-level
languages like C and C++.
• Arduino code is based on C++, a high-level
programming language
Languages of microcontroller
• C and C++ are popular languages for microcontroller
programming due to their low-level access to hardware
and high performance.
• These languages are widely used in embedded systems
development and offer a range of features and libraries
that make them suitable for various applications.
• C is a low-level, procedural, and compiled language that
was created in the 1970s. It is one of the most popular
and influential languages for microcontroller
programming due to its simple syntax, a small set of
keywords, and a rich library of functions.
What is Arduino?
• Microcontroller: The microcontroller used on the Arduino board is essentially used for
controlling all major operations. The microcontroller is used to coordinate the input taken and
execute the code written in a high-level language.
• Analog Reference pin: Analog pins are used for general purposes like supporting 10-bit analog-
to-digital conversion (ADC) which is performed using analog the Read() function. Analog pins are
particularly helpful since they can store 0-255 bits which is not possible using digital pins.
• Digital Pins: Digital pins are used for general purposes like taking input or generating output.
The commands that are used for setting the modes of the pins are pinMode(), digitalRead(), and
digitalWrite() commands.
• Reset Button: The reset button on the Arduino board is used for setting all the components of
Arduino to their default values. In case you want to stop the Arduino in between you can use
this reset button.
• Power and Ground Pins: As the name suggests, power and ground pins are used to supply the
power needed for driving the Arduino board. The ground pins are usually 0V to set a reference
level for the circuit.
• USB (universal serial bus): The Arduino needs certain protocols for communication purposes
and the universal serial bus is used for this purpose. It helps to connect Arduino,
microcontrollers with other raspberry pies.
Basic Operation
• Most Arduino boards are designed to have a single program
running on the microcontroller.
• This program can be designed to perform one single action, such
as blinking an LED.
• It can also be designed to execute hundreds of actions in a cycle.
The scope varies from one program to another.
• The program that is loaded to the microcontroller will start
execution as soon as it is powered. Every program has a function
called "loop". Inside the loop function, you can for example:
– Read a sensor.
– Turn on a light.
– Check whether a condition is met.
– All of the above.
Electronic Signals
• Analog Signal: Analog signals can take any
value in a given continuous range of values.
Generally, analog signals used in Arduino are
around 0V to 5V. The analog pins can take data
up to 8-bit resolution therefore, they are used
for taking large values as input in the Arduino.
These signals carry data in a very accurate
form without many errors.
Electronic Signals
• Digital Signal: Digital signals can only take discrete
values which are, high('1') and low('0'). These
signals are usually used to Arduino on or off which
requires only two values. The collection of two
values (0 and 1) can be used to generate a
sequence known as the binary sequence which is a
collection of zeroes and ones. This is how data is
transmitted without much memory requirement
but this can lead to certain errors like quantization
errors.
Electronic Signals
Analog Signal Digital Signal
• Digital signals can only take discrete
• Analog signals can take any value values which are, high('1') and
in a given continuous range of low('0').
values. • These signals are usually used to
• Generally, analog signals used in Arduino on or off which requires only
two values.
Arduino are around 0V to 5V.
• The collection of two values (0 and 1)
• The analog pins can take data up can be used to generate a sequence
to 8-bit resolution therefore, known as the binary sequence which
they are used for taking large is a collection of zeroes and ones.
values as input in the Arduino. • This is how data is transmitted
• These signals carry data in a very without much memory requirement
accurate form without many but this can lead to certain errors like
errors. quantization errors.
Brackets
• There are two types of brackets utilized in Arduino coding, as
given below:
• Parentheses: When writing a function in IDE, the parentheses
brackets are used to include the argument parameters, such as
methods, functions, or code statements. In addition to this, the
bracket is also used for defining the precedence order while
dealing with mathematical equations. These brackets are
represented by '( )'.
• Curly Brackets: Curly brackets are used to open and close all the
statements in the functions or out of the functions. Note that a
closed curly bracket always follows the open curly bracket in the
code for proper layout. These brackets are denoted by '{ }'.
– Open curly bracket- ' { '
– Closed curly bracket - ' } '
Line Comment
• There are two types of line comments, let us study them individually:
• Single-line comment: As the name suggests, the single lines that follow
two forward slashes are known as single-line comments. These
statements are known as comments because the compiler ignores all the
characters that come after two forward slashes in a single line.
Comments are hidden when the output is presented. Comments are
added for the sole purpose of comprehension of the code and for writing
necessary information for user reference.
// This is a comment
• Multi-line comment: The single line comment extends to one line and
the Multi-line comment is used for adding comments in multiple lines.
The syntax is a forward slash followed by an asterisk symbol (/*), ending
with a */. It is mostly used for commenting larger text blocks that are not
interpreted by the compiler and solely for reference purposes of users.
/ * This is a multiline comment*/
Coding Screen
• If you open the coding screen of your IDE, you
will realize that it is divided into two sections
namely, setup() and loop(). The setup
segment is the first block and is implemented
first for preparing the necessary environment
needed for running other commands. This
coding screen is shown below:
Coding
• It is important to note that the setup and loop
blocks must have statements that are
enclosed within curly brackets. Depending on
the type of project you are working on, you
can initialize the setup in setup() and define
other necessary statements in the loop()
block. Let us study each section individually
Coding
• It is important to note that the For example
setup and loop blocks must void setup ( ) {
have statements that are Coding statement 1;
enclosed within curly brackets. Coding statement 2;
• Depending on the type of Coding statement n;
}
project you are working on, you
void loop ( ) {
can initialize the setup in setup()
Coding statement 1;
and define other necessary
Coding statement 2;
statements in the loop() block.
Coding statement n;
• Let us study each section }
individually
Coding
• Setup contains the very beginning section of the code that must be executed
first. The pin modes, libraries, variables, etc., are included in the setup section
so that no problem occurs when the remaining code runs. It is executed only
once during the uploading of the program and after resetting or powering up
the Arduino board.
• Zero setup () resides at the top of each sketch. When the program runs after
completion, it heads towards the setup section to initialize the setup and
include all the necessary libraries all at once.
• Loop The loop contains statements that are executed repeatedly. Unlike, the
setup section there is no restriction on running this code once, it can run
multiple times according to the value of variables.
• Time The basic unit of measuring time in Arduino programming is a
millisecond.
1 sec = 1000 milliseconds
• Timing adjustments can be made in milliseconds. A better explanation for this
can be that a 2-second delay corresponds to 2000 milliseconds.
Simple example
• A of blinking the LED using Arduino is
considered.
The steps are:
• Go to the menu bar. Click on the File button in
the bar.
• Click on the Examples in the menu bar.
• Click on the Basics option.
• You will see Blink, click it.
• Note: The pinMode will be the main function
in the void setup() and digitalWrite( ) and
delay ( ) will be the main function in the void
setup()
PinMode ( )
• The pinMode() function assigns a specific PIN as either
INPUT or OUTPUT.
The Syntax is:
pinMode (pin, mode)
• Pin: It is used to specify the PIN which depends on the
project requirements.
• Mode: Depending on whether the pin is taking INPUT or
OUTPUT, it specifies the pin's function.
• Let's consider a situation to understand the pinMode. We
want to take input from the PIN 13 and then,
• Code:
pinMode (13, INPUT);
PinMode in OUTPUT mode
• Setting pinMode to OUTPUT is important for
some pins. This mode allows the specified PIN to
supply sufficient current to another circuit to
activate the sensor or light the LED. When set to
OUTPUT, this pin goes into a very low impedance
state, making the current useful. It is important to
note that excessive current or short circuits
between pins can damage the Atmel chip. This
explains the need for setting the mode to
OUTPUT.
PinMode in INPUT mode
• When digitalWrite() is used, selecting the INPUT
mode for any pin turns off the low state and sets the
high state as the ultimate state. The INPUT mode
can be employed alongside an external pull-down
resistor. For this purpose, pinMode should be set to
INPUT_PULLUP. This configuration reverses the
behavior of the INPUT mode. In INPUT_PULLUP
mode, a sufficient current is provided to light an LED
connected to the pin dimly. If the LED emits a dim
light, it signifies that this condition is operational.
digitalWrite( )
• Pin: We can specify the PIN or the declared variable.
Let's understand with an example.
Example:
digitalWrite (6, HIGH);
digitalWrite (6, LOW);
• The HIGH will be used for setting the pin at number
6 high and it will ultimately turn on the LED if
connected to this pin while, the LOW will be used
for setting the pin at number 6 low and it will
ultimately turn off the LED if connected to this pin.
delay ( )
• The delay() function • Code:
digitalWrite (12, HIGH);
serves as a tool to halt
delay (5000);
program execution for a
digitalWrite (12, LOW);
specified duration, delay (2000);
measured in milliseconds. • The program here is that the LED is
We have seen how connected to the pin having PIN 12
delay(5000) signifies a and it will remain lit for 5 seconds
before turning and then will go off.
stop of 5 seconds. • The LED will then be turned off for
• This can be understood 2 seconds as specified by delay().
by the fact that 1 second This cycle will continue in a loop
depending on the defined variables
equals 1000 milliseconds. within the void loop() function.
Solved Example
• Let us try to code the control of the LED on
PIN 13, by designing it to remain ON for 1
seconds and remain OFF for 1 seconds. Here
is the code
EXAMPLE
• Firstly, we will need to set a particular pin as the output
pin therefore, we will set the pin number 12 as the input in
setup() block.
• Then we need to set the pin number 12 high using the
digitalWrite() function.
• Then we use the delay() function to keep the LED on for 3
seconds.
• Then we need to set the pin number 12 low using the
digitalWrite() function.
• Then we use the delay() function to keep the LED off for 2
seconds.
EXAMPLE
void setup ()
{
pinMode ( 13, OUTPUT); // to set the OUTPUT mode of pin number 13
}
void loop () {
digitalWrite (13, HIGH);
delay (1000); // 1 seconds = 1 x 1000 milliseconds
digitalWrite (13, LOW);
delay (1000); // 1 seconds = 1 x 1000 milliseconds
}
Write arduino program for Traffic light
• Green light for 5 seconds
• Yellow light for 2 seconds
• Red light for 5 seconds
Traffic light code
int RED= 9; void loop() {
int YELLOW= 8; digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, LOW);
int GREEN = 7; digitalWrite(RED, LOW);
void setup() delay(5000);
digitalWrite(GREEN, LOW);
{ digitalWrite(YELLOW, HIGH);
digitalWrite(RED, LOW);
pinMode(RED, OUTPUT); delay(2000);
pinMode(YELLOW, digitalWrite(GREEN, LOW);
OUTPUT); digitalWrite(YELLOW, LOW);
digitalWrite(RED, HIGH);
pinMode(GREEN, OUTPUT);
delay(5000);
} }
Interfacing LDR to arduino
• LDR can stand for light-dependent resistor
• A light-dependent resistor (LDR) is a passive electronic component
that changes resistance based on the amount of light it receives.
• LDR reads at bright time up to 100 ohm, at dark time up to 1Mohm
• LDRs are also known as photo resistors or photo-conductive cells.
• LDRs are used in many applications, including automatic door
opening, security lights, and solar cells.
• LDRs are made of semiconductors and are sensitive to light.
• LDRs are compact and have low power requirements.
• LDRs are used in automation systems to detect objects without
physical contact.
Wiring diagram
Arduino Code
const int LIGHT_SENSOR_PIN = A0;
const int LED_PIN = 3;
const int ANALOG_THRESHOLD = 500;
int analogValue;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
analogValue = analogRead(LIGHT_SENSOR_PIN);
if(analogValue < ANALOG_THRESHOLD)
digitalWrite(LED_PIN, HIGH);
else
digitalWrite(LED_PIN, LOW);
}
Interface arduino to Liquid crystal display
LCD
• The LCDs have a parallel interface, meaning that the
microcontroller has to manipulate several interface pins at once to
control the display. The interface consists of the following pins:
• A register select (RS) pin that controls where in the LCD's memory
you're writing data to. You can select either the data register, which
holds what goes on the screen, or an instruction register, which is
where the LCD's controller looks for instructions on what to do
next.
• A Read/Write (R/W) pin that selects reading mode or writing mode
• An Enable pin that enables writing to the registers
• 8 data pins (D0 -D7). The states of these pins (high or low) are the
bits that you're writing to a register when you write, or the values
you're reading when you read.
To wire your LCD screen to your board, connect
the following pins:
• LCD RS pin to digital= pin 12
• LCD Enable pin to digital= pin 11
• LCD D4 pin to digital= pin 5
• LCD D5 pin to digital =pin 4
• LCD D6 pin to digital =pin 3
• LCD D7 pin to digital= pin 2
• LCD R/W pin to GND
• LCD VSS pin to GND
• LCD VCC pin to 5V
• LCD LED+ to 5V through a 220 ohm resistor
• LCD LED- to GND
Code to prints Hello World! to the LCD
// include the library code:
#include <LiquidCrystal.h>
// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis() / 1000);
}
Connect keypad to arduino
keypad
3x4 keypad 4x4 keypad
• The 3x4 keypad has 7 • 4x4 Keypad. Keypad is used as an
pinouts. input device to read the key
pressed by the user and to process
• Four of these pins are it.
connected to each row of the • 4x4 keypad consists of 4 rows and 4
keypad, and the remaining columns.
three pins are connected to • Switches are placed between the
each column of the keypad. rows and columns.
• A key press establishes a
• Pressing a key shorts one of
connection between the
these pins to another of the corresponding row and column,
pins. between which the switch is
placed.
keypad and arduino microcontroller
#include <Keypad.h>
const int ROW_NUM = 4; //four rows
const int COLUMN_NUM = 3; //three columns
char keys[ROW_NUM][COLUMN_NUM] = { {'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'} };
byte pin_rows[ROW_NUM] = {9, 8, 7, 6};
//connect to the row pinouts of the keypad
byte pin_column[COLUMN_NUM] = {5, 4, 3};
//connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column,
ROW_NUM, COLUMN_NUM );
void setup(){ Serial.begin(9600); }
void loop()
{ char key = keypad.getKey(); if (key)
{ Serial.println(key); } }
Keypad and LCD projects
Room temperature controlling using
arduino
Water level control using arduino and
ultrasonic sensor