Microprocessor Module
Microprocessor Module
Objectives:
Microprocessor
The addition of external hardware makes these bulkier and much more expensive. However,
this makes it versatile, the designer can decide on the amount of RAM, ROM and I/O ports
needed to fit the required system.
Microcontroller
Page 1
A microcontroller or MCU has a microprocessor in addition to a fixed amount of RAM, ROM, I/O
ports and a timer all on a single chip. In other words, the processor, RAM, ROM, I/O ports and
time r are all embedded together on one chip.
Features of
Microcontroller
Clock generator – often as oscillator for a quartz timing crystal, resonator or RC circuit
Microcontroller is inexpensive
Microcontroller I/O ports are easily accessible in comparison with computer I/O
Disadvantages of Microcontroller
Architecture
Von Neumann – program and data are stored in one memory bank.
Provider
AVR
(Alf and
Vegard’s
RISC Processor)
– developed
by Atmel
service provider
based on Harvard
architecture
PIC (Peripheral Interface Controller) – based on Harvard architecture supports
programming in C, Assembly and BASIC C, made by Microchip technology.
Page 3
Hitachi – belongs to H8 family of the controller, (8-bit, 16-bit and 32-bit
microcontroller), developed by Renesas Technology in Hitachi semiconductors. Motorola –
highly integrated microcontroller that is used for high-performance data manipulation operation,
uses a System Integration Module (SIM), Time Processing Unit (TPU) and Queued Serial
Module 9QSM).
Embedded System
Page 4 Embedded systems are becoming an essential part of any product or equipment
in all fields
including:
A PC can be used for any number of applications such as word processor, print server, bank
teller terminal, video game player, network server or internet terminal. Software for a variety of
applications can be loaded and run. PC can perform variety of tasks because it has operating
system that loads application software to memory to run it.
Embedded system uses only one application software that is typically burned into ROM.
Arduino Uno R3 Microcontroller Board – the cheapest, ready to connect board with
various available online libraries and resources.
Arduino Pro Mini 328 – this mini board is only for small-scale applications up to 5 volts.
ESP32 Microcontroller Board – Bluetooth and Wi-Fi duo combo on a single-chip, bit
costly used for smart home and IoT based projects.
Raspberry Pi 4 – fastest microcontroller with 4GB RAM, wireless LAN, Bluetooth, USB
port, HDMI ports and Ethernet port.
MBED LPC1768 – mostly designed for prototyping applications, with I/O peripherals,
USB port and Ethernet port.
Quark D2000 – one of the most robust microcontroller and has more I/O controls.
Launchpad MSP430 – most useful for application of Energy Trace on-board emulation
and debugging.
Page 5
Module 2: Exploring the Arduino Board
Objectives:
Arduino
Page 6
Arduino does not need a separate piece of hardware (called a programmer) to load new code
onto the board, simply a USB cable.
Simple, clear programming environment – easy-to-use for beginners, yet flexible enough
for advanced users to take advantage of as well.
Open source and extensible software – open source tools, available for extension by
experienced programmers.
Open source and extensible hardware – experienced circuit designers can make their
own version of the module.
Syntax – need to memorize the syntax and sketches in programming the Arduino.
History of Arduino
2005 – Hernando Barragan created the development platform Wiring as a Master’s thesis
project at IDII (Interaction Design Institute Ivrea) in Ivrea, Italy. Massimo Banzi and David
Cuartielles created Arduino. David Mellis developed the Arduino software. Gianluca Martino
and Tom Igoe joined the project.
Page 7
The First Arduino Board
Arduino Boards
Microcontroller type;
Microcontroller speed (frequency);
Physical size;
Number of input and output pins;
Memory space for programs
Price
Page 8
Arduino Uno Arduino Leonardo
Arduino Due
Page 9
Comparison Between Arduino Boards
Operating
CPU Analog Digital EEPROM SRAM Flash
Name Processor Voltage/Input USB UART
Mega
ATmega2560 5V/7-12V 16Mhz 16/0 54/15 4 8 256 Regular 4
2560
ATmega168 .512 1 16
Nano 5V/7-9V 16Mhz 8/0 14/6 Mini-B 1
ATmega328 1 2 32
Arduino Shields
A shield is a circuit board that connects via pins to the sockets on the sides of an Arduino.
GSM Shield
The GSM Shield with a SIM card allows an Arduino board to connect to the internet,
make/receive voice calls and send/receive SMS messages.
Ethernet Shield
The Ethernet Shield allows an Arduino board to connect to the internet. It provides a network
(IP) stack capable of both TCP and UDP.
Page 9 Wi-Fi Shield
The Wi-Fi Shield allows an Arduino board to connect to the internet using the 802.11 wireless
specification (Wi-Fi). It provides a network (IP) stack capable of both TCP and UDP.
Arduino UNO
Parts
ATmega382 microcontroller
16Mhz clock
6 analog inputs
ICSP header
USB connection
Power jack
Reset button
LEDs
USB (Universal Serial Bus)
It Connects the board to a computer for three reasons:
Page 11
Upload code to the Arduino
Power Connector
Microcontroller
It executes instructions.
Power Pins
3.3V – this pin outputs a regulated 3.3V from the regulator on the board.
IOREF – this pin on the Arduino board provides the voltage reference with which the
microcontroller operates.
Analog Pins
Page 12
Digital Input/Output Pins
Arduino IDE
The open-source software where to write and compile the code for Arduino.
Using the IDE is a 3-step process:
Upload to Arduino
Page 13
Code St ructure
Page 14
Module 3: Arduino Programming
Objectives:
Arduino Sketch
An Arduino sketch is a set of instructions (program) that you create to accompl ish a certain task.
Setup Function
Loop Function
voidsetup() {
// put your setup code here, to run once
}
voidloop() {
// put your main code here, to run repeatedly
}
Setup Function
Page 15
The setup() function is called when a sketch starts.
The setup function will only run once, after each power up or reset of the Arduino board.
Loop Function
The loop() function does precisely what its name suggests and loops consecutively,
allowing the program to change and respond as it runs.
Code in the loop() section of the sketch is used to actively control the Arduino board.
Sample Program
void setup() {
initialize and start the serial
port Serial.begin(9600);
void loop() {
}
Any line that starts with two slashes (//) is a comment and will not be read by the
compiler.
Comments in the code give label and explain the task of that line of code.
Serial class is used for communication between the Arduino board and a computer or other
devices.
Page 16
Variable Type
It tells the compiler what type or how data will be used in the program.
Void type
void setup() {
// put your setup code here, to run once
}
Boolean type
Char type
The char variable stores a character value. Each char variable occupies one byte (8bits) of
memory.
Character literals are written in single quotes (‘A’). Characters are stored as number using
ASCII encoding. This means that is it possible to do arithmetic on characters, in which
the ASCII value of the character is used (‘A’ + 1 = 66).
The char data type is a signed type, that is encodes numbers from -128 to 127.
Byte type
Page 17
The byte variable stores 8-bit unsigned number, from 0 to 255.
An int variable stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767.
The unsigned int is the same as the int type however, it only stored positive values,
from 0 to 65,535.
int x = -13;
unsigned int y = 13;
A long variable can stores 32-bits (4-byte), from -2,147,483,648 to 2,147,483,647. If doing
math with integers, at least one of the numbers must be followed by an L, forcing it to be
a long.
An unsigned long variable can stores 32-bits (4-byte). It does not store negative
numbers, making its range from 0 to 4,294,967.295.
long s = -18600L;
unsigned long v = 18600L;
A float variable is used to express floating-point numbers (with decimal point). Floatingpoint
numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are
stored as 32-bits (4-byte).
On most Arduino boards, double is the same size as float. On Arduino Due, double has
64-bits (8-byte).
If doing math with float, it needs to add a decimal point, otherwise it will be treated as an
int.
Page 18
int x;
int y;
floatz;
x = 1;
y = x / 2;// y now contains0, int can't hold fractions
z = (float)x / 2.0;// z now contains 0.5 (use 2.0, not 2)
Arrays
Declaring an Array
It can declare an array without explicitly choosing a size, as in MyPins (compiler counts
the elements and creates an array of the appropriate size).
myPins[0] = 2 mySensVals[1] = 4
myPins[2] = 8 mySensVals[2] = -8
myPins[4] = 6 mySensVals[5] = 7
Page 19
Assigning and Retrieving Values from Arrays
x = myPins[3]; y = mySensVals[4];
therefore:
x=3 y=2
Page 20
Strings
Char-Array
o Declare an array of chars (with one extra char) and the compiler will add the
required null character, as in Str2
o Explicitly add the null character, as in Str3
o Initialize with a string constant in quotation marks; the compiler will size the array
to fit the string constant and a terminating null character, as in Str4
o Initialize the array with an explicit size and string constant, as in Str5 o Initialize
the array, leaving extra space for a larger string, as in Str6
char Str1[15];
char Str3[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'};
Generally, strings are terminated with a null character (ASCII code 0).
This allows functions (like Serial.print()) to tell where the end of a string is.
Otherwise, they would continue reading subsequent bytes of memory that aren't
actually part of the string.
This means that the string needs to have space for one more character than the
text wants to contain.
That is why Str2 and Str5 need to be eight characters, even though "arduino" is
only seven - the last position is automatically filled with a null character.
Str4 will be automatically sized to eight characters, one for the extra null.
Page 19
In Str3, we've explicitly included the null character (written '\0') ourselves.
Note that it's possible to have a string without a final null character (e.g. it had
specified the length of Str2 as seven instead of eight).
This will break most functions that use strings, so it shouldn't do it intentionally.
Strings are always defined inside double quotes ("Abc") and characters are
always defined inside single quotes('A').
Arrays of strings
It is often convenient, when working with large amounts of text to setup an array
All array names are actually pointers, so this is required to make an array of
arrays.
Pointers are one of the more esoteric parts of C for beginners to understand.
char* myStrings[]={"This is string 1",
"This is string 2",
"This is string 3",
"This is string 4",
"This is string 5", "This is string 6"};
Page 20
String-object
The String class allows to use and manipulate strings of text in more complex ways than
characters array do.
It can concatenate strings, append to them, search for and replace substrings, and
more.
It takes more memory than a simple character array, but it is also more useful.
o StringAdditionOperator o StringIndexOf
o StringAppendOperator o
StringLengthTrim
o StringCaseChanges
o StringReplace
o StringCharacters
o StringStartsWithEndsWith o
StringComparisonOperators o StringSubstring
Constants
Constants are predefined variables in the Arduino language.
Logical Levels
o Pin Levels
o Digital Pins
Page 21
Logical Levels
There are two constants used to represent truth and falsity in the Arduino language:
o FALSE – false is defined as 0 (zero)
o TRUE – true is often said to be defined as 1, which is correct, but true has a
wider definition, Any integer which is non-zero is true, in Boolean sense.
Pin Levels
When reading or writing to a digital pin there are only two possible values:
LOW - The meaning of LOW also has a different meaning depending on whether a
pin is set to INPUT or OUTPUT. When a pin is configured as an INPUT, the
microcontroller will report LOW if a voltage of 2 volts or less is present at the pin.
When a pin is configured to OUTPUT and set to LOW, the pin is at 0 volts.
Digital Pins
Page 22
Integers
By default, an integer constant is treated as an int with the attendant limitations in values.
To specify an integer constant with another data type, follow it with:
o a 'u' or 'U' to force the constant into an unsigned int data format. Example: 33u
o a 'l' or 'L' to force the constant into a long data format. Example: 100000L o a
'ul' or 'UL' to force the constant into an unsigned long constant. Example:
32767UL
Normally, integer constants are treated as base 10 (decimal) integers, but special notation
(formatters) may be used to enter numbers in other bases:
o Decimal is base 10
Constants without other prefixes are assumed to be in decimal format.
Binary is base 2
Only characters 0 and 1 are valid. The binary formatter only works on
bytes (8 bits) between 0 (B0) and 255 (B11111111). Example: B101 //
same as 5 decimal
Octal is base 8
Only characters 0 through 7 are valid. Octal values are indicated by the
prefix "0“. Example: 0101 // same as 65 decimal
Hexadecimal is base 16
Valid characters are 0 through 9 and letters A through F. Note that A-F
may be written in upper or lower case (a-f). Hex values are indicated by
the prefix "0x". Example: 0x101 // same as 257 decimal
Floating Point
Similar to integer constants, floating point constants are used to make code more
readable. Example: 0.005
10.0 = 10
^
2.34E5 = 2.34 x 10 5 = 234000
-12
67e-12 = 67.0 x 10 = 0.000000000067
Page 23
Operators
Arithmetic Operators
i
n
t
x
9
;
z = x + y; // z
= 11 (9+2=11) z
= x - y; // z =
7 (9-2=7) z = x
* y; // z = 18
(9*2=18) z =
x / y; // z = 4
(9/2=4 not 4.5)
z = x % y; // z
= 1 (remainder
of 9/2 = 1)
Comparison Operators
(x == y) // (9 == 2) false
(x == z) // (9 == 9) true
(x != y) // (9 != 2) true
(x != z) // (9 != 9) false
(x < y) // (9 < 2) false
(x < z) // (9 < 9) false (x
> y) // (9 > 2) true
(x > y) // (9 > 9) false
(x <= z) // (9 <= 9) true
(x >= z) // (9 >= 9) true
Page 24
Boolean Operators
int x = 8; int y = 2;
// T: (8<7)=F
!(x < 7)
!(x > 7) // F: (8>7)=T
Bitwise Operators
x = 92; y = 101;
int // in binary: 0000000001011100 int // in
Page 25
Compound Operators
int y = ++x; // y = 6; x = 6
x += 2; // x = 7 (x = 5 + 2)
x *= 2; // x = 10 (x = 5 * 2)
x /= 2; // x = 2 (x = 5 / 2)
x &= 2; // x = 0 (x = 0…0101 & 0…0010 = 0…0000)
Control Structures
Flow Control
The if statement
if (boolean_experssion) {
// statement(s)
}
Rules:
If the Boolean expression evaluates to true, then the block of code
inside the if statement will be executed. If the Boolean
expression evaluates to false, then the first set of code after the
end of the if statement
if (boolean_experssion) {
// statement(s)
}
else {
// statement(s)
}
Rules:
If the Boolean expression evaluates to true, then the if block of
code will be executed, otherwise else block of code will be
executed.
Page 27
Rules:
The expression must have an integral or enumerated type.
The default case can be used for performing a task when none of
the cases is true.
Looping Construct
while (condition) {
//statement(s)
}
Rules:
Page 32
The condition may be any expression. The loop iterates while the
condition is true. When the condition becomes false, program
control passes to the line immediately following the loop.
int i = 3; while*
(i < 5) { *
Serial.println(
}
do {
//statement(s)
} while (condition);
Rules:
The statement(s) in the loop execute once before the condition is
tested. If the condition is true, the flow of control jumps back up
to do, and executes the statement(s) again. This process repeats
until the given condition becomes false.
int i = 3; *
do { *
*
Serial.println(
} while (i < 5
Page 33
Rules:
The init step is to initialize the loop control variable(s).
After the body of the for loop executes, the flow of control jumps back
up to the increment statement. This statement allows you to
update the loop control variable(s).
If it is true, the loop executes and the process repeats itself (body
of loop, then increment step, and then again condition).
Functions
Functions are used to organize the actions performed by your sketch into functional blocks.
Structure
Maintain
o Reuse
Page 34
User Defined Function
o Name
o Optional parameter
Page 35
Predefined Function
Time Functions
millis() : Returns the number of milliseconds since the Arduino board began
running the current program.
micros() : Returns the number of microseconds since the Arduino board began
running the current program.
delay() : Pauses the program for the amount of time (in milliseconds) specified
as parameter.
Math Functions
Page 31
Trigonometry Functions
Random Numbers
External Interrupts
Page 32
Module 4: Arduino Interfacing
Objectives:
Arduino Connection
Arduino can use same USB cable for programming and to talk with computers.
TX – sending to PC
RX – receiving from PC
Serial Communications
Serial Communications
“Serial” because data is broken down into bits, each sent one after the other down a single
wire.
You could implement sending serial data with digitalWrite() and delay()
But serial communication is also possible using software libraries to emulate additional
ports.
Page 34
Arduino to Computer
All programs that talk to Arduino (even the Arduino IDE) think that they’re talking via a serial
port
Sides must agree how information is organized in the message (communications protocol)
Header - one or more special characters that identify the start of message
Footer - one or more special characters that identify the end of message
println() – prints the data followed by a carriage return character and a newline
character
Floats are similarly printed as ASCII digits, defaulting to two decimal places o
Bytes are sent as a single character
Baud Rate
Use the same speed for the sending side and the receiving side.
Page 36
Module 5: Digital Output
Objectives:
Interfacing LEDs
A Light Emitting Diode or LED is basically a specialized type of PN junction diode capable of
emitting light when conducting.
o Direction signs
o Advertising
o Traffic signals
Page 37
DC Characteristics and Operation
Forward voltage (VF) which is the minimum required voltage to turn on the LED
o Full Drive/Forward Current (IF) which is the maximum allowed current across
the LED (i.e. a current larger than IF will burn the LED).
To make a pin an output, it needs to first tell the Arduino how the pin should be configured
(INPUT/OUTPUT).
Page 38
In the Arduino programming language, the program requires two parts:
The setup() function runs one time at the start of the program, and the loop() function runs
over and over again.
Since it dedicates each pin to serve as either an input or an output, it is common practice to
define all your pins as inputs or outputs in the setup.
pinMode(9, OUTPUT);
The pinMode() function configures the specified pin to behave either as an input or
an output. o Syntax:
o
Parameters pinMode(pin, mode) pin:: the number of the pin whose mode you wish to set.
None
Page 39
Writing Digital Outputs
Because the loop() function runs over and over again, outputs are usually written in this
function.
void loop() {
digitalWrite(9, HIGH);
If the pin has been configured as an OUTPUT with pinMode(), its voltage will be
set to the corresponding value: 5V for HIGH, 0V for LOW.
Syntax:
None
Sample: Arduino program that turns ON an LED connected to pin 13 for 1 second, then OFF
for 1 second, repeatedly.
Turns on an LED on for one second, then off for one second,
repeatedly. int led = 13;
Page 40
The delay Function
The delay() function Pauses the program for the amount of time (in milliseconds)
specified as parameter. o Note: there are 1000 milliseconds in a second.
Syntax delay(ms):
o Parameters:
Page 41
Module 6: Digital Input
Objectives:
A push button allows a voltage or current to pass when the button is pressed.
Push buttons are generally used as reset switches and pulse generators.
Page 42
Interfacing Push Button to Arduino
(1) Pull-Up Resistors: In this case, the output of the button is normally HIGH
and when the button is pressed it generates a LOW pulse (Figure 1).
(2) Pull-Down Resistors: In this case, the output of the button is normally LOW
and when the button is pressed it generates a HIGH pulse (Figure 2).
Page
43
Since it dedicates each pin to serve as either an input or an output, it is common practice to
define all your pins as inputs or outputs in the setup.
void setup() {
pinMode(9, INPUT);
The pinMode() function configures the specified pin to behave either as an input or
an output. o Syntax :
pinMode(pin, mode)
Parameters pin: the number of the pin whose mode you wis: h to set.
mode: INPUT or OUTPUT Returns :
None
Page 44
Reading Digital Inputs
Because the loop() function runs over and over again, inputs are usually read in this
function.
int pinState;
void loop() {
pinState = digitalRead(4);
The digitalRead() function reads the value from a specified digital pin, either HIGH or
LOW.
Syntax digitalRead(pin):
o Parameters: o Retu rn: pin: the number of the digital pin you want to
read (int) .
HIGH or LOW
Sample: Arduino program that repeatedly reads the state of a push button connected to pin 4
and display the message “Button Pressed” on the Arduino environment’s built-in serial monitor
whenever the button is pushed.
Repeatedly Reads
the state of a bush button connected to pin 4,
and displays the message
“Button Pressed
” whenever the button
is pushed.
int buttonState;
Page 45
Switch Bounce
Push buttons exhibit a phenomenon called switch bounce, or bouncing, which refers to a
button’s tendency to turn on and off several times after being pressed only once by the
user.
This phenomenon occurs because the metal contacts inside a push button are so small that
they can vibrate after a button has been released, thereby switching on and off again
very quickly.
Switch Bounce can cause wrong behavior of digital circuits due to reading multiple values
for a single press of the button.
Switch
Debounce
Basic Idea:
look for a button state change, wait for the bouncing to finish, and then reads the
switch state again.
Page 46
This software logic can be expressed as follows:
o 3. If the current button state differs from the previous button state, wait 5ms
because the button must have changed state.
o 4. After 5ms, reread the button state and use that as the current button state.
o 5. Set the previous button state to the current button state.
o 6. Return to step 2.
// Modify previous program to debounce the switch
int buttonState; // the current reading from the input int pin
previousButtonState LOW;= // the previous reading from the input pin
longlastDebounceTime = 0; // the last time the output
n waspitoggled
longdebounceDelay = // 50;the debounce time;
void
setup() {
pinMode(4, OUTPUT);
Serial.begin(9600);
}
voidloop() {
read the state of the switch into a local
variable: int reading = digitalRead(4);
If the switch changed, due toornoise
pressing: if (reading!= lastButtonState){
reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
the reading has been there for longer than the debounce delay, so take
it if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) { // if pin state is HIGH
Serial.println(
“Button Pressed
”); // display the message
}
}
}
// save the reading
lastButtonState = reading;
}
The millis() function returns the number of milliseconds since the Arduino board began
running the current program.
o This number will overflow (go back to zero), after approximately 50 days.
o Syntax:
o
Parameters None.millis() :
o Return :
Number of milliseconds since the program started (unsigned long)
Page 47
Module 7: Enhanced Digital Output
Objectives:
7-Segment Display
Each one of the seven LEDs in the display is given a positional segment which is controlled
by one pin.
These LED pins are labeled a, b, c, d, e, f, and g representing each individual LED.
Page 48
The other LED pins are connected together and wired to form a common pin.
By forward biasing the appropriate pins of the LED segments, some segments will be light
and others will be dark allowing the desired character pattern of the number to be
generated on the display.
This allows to display each of the ten decimal digits 0 through to 9 on the same 7-segment
display.
The displays common pin is generally used to identify which type of 7-segment display it is.
As each LED has two connecting pins, one called the “Anode” and the other called the
“Cathode”.
Common Cathode
In the common cathode display, all the cathode connections of the LED segments are joined
together to logic “0″ or ground.
The individual segments are illuminated by application of a “HIGH”, or logic “1″ signal via
a current limiting resistor to forward bias the individual Anode terminals (a-g).
Common Anode
Depending upon the decimal digit to be displayed, the particular set of LEDs is forward
biased.
The various digits from 0 through 9 can be displayed using a 7-segment display.
Page 50
seven individual LEDs within a single package and as such these LEDs need
protection from over-current.
LEDs produce light only when it is forward biased with the amount of light emitted being
proportional to the forward current. This means that an LEDs light intensity increases
in an approximately linear manner with an increasing current. So this forward current
must be controlled and limited to a safe value by an external resistor to prevent
damaging the LED segments.
The forward voltage drop across a red LED segment is very low at about 2-to-2.2 volts. To
illuminate correctly, the LED segments should be connected to a voltage source in
excess of this forward voltage value with a series resistance used to limit the forward
current to a desirable value.
Typically for a standard red colored 7-segment display, each LED segment can draw about
15mA to illuminated correctly, so on a 5 volt digital logic circuit,
o the value of the current limiting resistor would be about 200Ω (5v – 2v)/15mA, or
o 220Ω to the nearest higher preferred value.
So to understand how the segments of the display are connected to a 220Ω current limiting
resistor consider the circuit below.
Page 51
BCD to 7-Segment Decoder
The 7-segment Display is usually driven by a special type of integrated circuit (IC) known as
a BCD to 7-segment decoder.
latch/decoder/driver.
Its function is to convert a BCD digit into signals which will drive a 7-segment display.
Inputs:
Outputs:
seven buffered segment outputs (Qa- Qg).
Page 52
The functions of the three control inputs PH, BL and LE are as follows: o
The phase (PH) input is used to reverse the function table phase.
o The blanking (BL) input is used to blank (turn off) the display.
Page 53
Interfacing 7-Segment Display to Arduino
GFG1AB
E D G2CDP
Page 54
BCD Counter Sample Program
In this part, pins 0 to 4 are defined as output pins to control illumination of the 7 segments:
o Pins 0-3: control the address inputs (Dd, Dc, Db, Da) of the 4543 decoder o Pin
4: control the Latch Enable (LE) of the 4543 decoder.
Counter Logic
In this part, a FOR loop is used to implement the one-digit BCD counter logic with 1 second
delay.
Page 55
BCD Digit Display
In this part, a function is used to display the given decimal digit (BCD code) as follows: o (1)
Set the LE line of the 4543 decoder HIGH to write the received BCD code into
the 4543 decoder.
o (2) for each bit in the received BCD code do the following (a)
Determine the value of the bit (0 or 1). :
(b) Set the corresponding output pin (HIGH or LOW) accordingly.
(3) Set the LE line of the 4543 decoder LOW to latch (store) the received BCD
code into the 4543 decoder
Syntax :
bitRead(x, n)
o Returns: n : which bit to read, starting at 0 for the least -significant (rightmost) bit the value
Page 56
Module 8: Enhanced Digital Input
Objectives:
Scanning
the Keypad
When interfacing
the keypad
to a
microcontroller, this can be done using a very simple procedure called "key scanning".
o (1) Apply Logic 1 on column 1 and Logic 0 on remaining columns. o (2) Scan
the logic signals on all rows A to D.
o (3) If a Logic 1 is read on one row then this indicates that the corresponding key
(i.e. 1, 4, 7 or *) is pressed.
o (4) Repeat steps 1-3 for column 2 to determine if any of the keys (2, 5, 8 and 0)
is pressed.
Page 57
o (5) Repeat steps 1-3 for column 3 to determine if any of the keys (3, 6, 9 and #)
is pressed.
Interface a phone keypad to the Arduino Uno Board and write a simple program to display
the value of pressed key on the Arduino environment’s built-in serial monitor.
The code that will scan the keys and display the value of the pressed key on the Arduino
environment’s built-in serial monitor consists of the following main pars:
In this part, an array is declared to hold character values corresponding to the buttons of the
keypad.
In this part, we configure the digital pins of the Arduino board to scan the keypad: o
Configure pins 0-2 as output pins to control COL1-COL3 of the keypad. o
Configure pins 3-6 as input pins to read ROW1-ROW4 of the keypad.
Page 59
set pins 0-2 as outputs to control COL1-3 of the keypad
for (int col = 0; col < 3; col++) {
pinMode(col, OUTPUT);
}
In this part, scan the keypad and return the character value of the pressed key or NULL if no
key is pressed.
o (1) Set key value to null
o (2) For each pin (a) Set the column HIGH0-2 connected to COL 1-3 do the following
If the state of the row is HIGH the do then set key value to the
character corresponding to the pressed button
Page 60
Display Key Value Logic
In this part, use the getKey() function to get the value of the pressed key: o
Get key value using the function getKey().
o If the returned key value is not NULL then display the value on the serial monitor
Objectives:
LCD
Page 61
They are used in many embedded systems such as, digital clocks, watches, microwave
ovens, CD players etc.
LCD Features
The ability to display numbers, characters, symbols and graphics (LEDs are
limited to numbers and a few characters)
refreshing the LCD (LEDs must be refreshed by the CPU to keep displaying the
data)
Ease of programming for characters and graphics.
Page 62
LCD Types
There are basically two types of LCDs as far as the interfacing method is concerned:
(1) Parallel LCDs are the most commonly used ones and they are connected to
microcontrollers using four to eight data lines and some control lines.
(2) Serial LCDs are connected to microcontrollers using only one data line and
data is sent to the LCD using the RS232 serial communications protocol.
Serial LCDs are easier to use, but they cost a lot more than the parallel ones.
LCD
Sizes
characters per row for example: a 1 × 16 display has one row with 16
Page 63
LCD Pin Configurations
VDD:
provides +5V
RS (Register Select):
R/W (Read/Write):
R/W input allows the user to write information to the LCD or read information
from it.
R/W = 1 when reading; o
R/W = 0 when writing.
Page 64
E (Enable):
The enable pin is used by the LCD to latch information presented to its data pins.
When data is supplied to data pins, a high-to-low pulse must be applied to this
pin in order for the LCD to latch in the data present at the data pins.
This pulse must be a minimum of 450 ns wide.
D0–D7:
The 8-bit data pins, D0–D7, are used to send information to the LCD or read the
contents of the LCD’s internal registers.
To display letters and numbers, we send ASCII codes for the letters A–Z, a–z,
and numbers 0–9 to these pins while making RS = 1.
There are also instruction command codes that can be sent to the LCD
Page 65
Operation Modes
The LCD display can be operated using one of two operation modes: o
(1) 8-bit Mode:
D7 o (2) 4data/code is transferred 8data is transferred over data li-bit Mode: -bits at a time
over data lines D0nes D4-D7 (D0-D3 may float).-
One possible interface of the LCD display to the Arduino Uno Board in 8-bit mode is given
below:
RS = pin 10
D0 = pin 7
D1 = pin 6
D2 = pin 5
D3 = pin 4
D4 = pin 3
D5 = pin 2
D6 = pin 1
D7 = pin 0
Page 66
One possible interface of the LCD display to the Arduino Uno Board in 4-bit mode is given
below:
The LiquidCrystal library allows an Arduino board to control LCD displays based on the
Hitachi HD44780 (or a compatible) chipset.
4-bit mode or
8-bit mode
It uses
4 or 8 data lines
the RS control line,
Functions
o setCursor() o
write()
o print() o
cursor()
o noCursor() o
blink()
o noBlink() o
display() o
noDisplay()
o scrollDisplayLef
t() o
scrollDisplayRi
ght() o
autoscroll()
o noAutoscroll()
o leftToRight()
o rightToLeft()
o createChar()
Page 68
The LiquidCrystal() Function
Description:
The RW pin can be tied to ground instead of connected to a pin on the Arduino; if
so, omit it from this function's parameters.
Syntax:
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)
Parameters:
rs: the number of the Arduino pin that is connected to the RS pin on the LCD
rw: the number of the Arduino pin that is connected to the RW pin on the LCD
(optional)
enable: the number of the Arduino pin that is connected to the enable pin on the
LCD
d0, d1, d2, d3, d4, d5, d6, d7: the numbers of the Arduino pins that are
connected to the corresponding data pins on the LCD.
d0, d1, d2, and d3: are optional; if omitted, the LCD will be controlled using only
the four data lines (d4, d5, d6, d7).
Page 69
The begin() Function
Description:
Initializes the interface to the LCD screen, and specifies the dimensions (width
and height) of the display.
Syntax:
lcd.begin(cols, rows)
Parameters:
lcd: a variable of type LiquidCrystal
void setup() {
lcd.begin(16,2);
}
Description:
Clears the LCD screen and positions the cursor in the upper-left corner.
Syntax:
lcd.clear()
Parameters:
Page 71
LiguidCrystal lcd new
= LiquidCrystal(11,10,3,2,1,0);
void setup() {
lcd.begin(1
6,2);
lcd.clear();
}
Description:
That is, use that location in outputting subsequent text to the display.
Syntax:
lcd.home()
Parameters:
void setup() {
lcd.begin(16,2);
lcd.home();
}
Description:
Position the LCD cursor; that is, set the location at which subsequent text written to
the LCD will be displayed.
Syntax:
lcd.setCursor(col, row)
Page 72
Parameters:
lcd: a variable of type LiquidCrystal
col: the column at which to position the cursor (with 0 being the first column)
o row: the row at which to position the cursor (with 0 being the first row)
void setup() {
lcd.begin(16,2);
lcd.setCursor(4,
1);
}
Description:
Syntax:
lcd.write(data)
Parameters:
void setup() {
lcd.begin(16,2);
lcd.write(
‘a’);
}
Description:
Page 73
Prints text to the LCD.
Syntax:
lcd.print(text)
Parameters:
Page 74
The cursor() Function
Description:
Display the LCD cursor: an underscore (line) at the position to which the next
character will be written.
Syntax:
lcd.cursor()
Parameters:
void setup() {
lcd.begin(16,2);
lcd.cursor();
}
Description:
Syntax:
lcd.noCursor()
Parameters:
void setup() {
lcd.begin(16,2);
lcd.noCursor();
}
Page 75
The blink() Function
Description:
If used in combination with the cursor() function, the result will depend on the
particular display.
Syntax:
lcd.blink()
Parameters:
}
void loop() {
lcd.noblink();
delay(500);
lcd.blink();
}
Description:
Syntax:
lcd.noBlink()
Parameters:
Page 76
LiguidCrystal lcd new
= LiquidCrystal(11,10,3,2,1,0);
}
void loop() {
lcd.noblink();
delay(500);
lcd.blink();
}
Description:
Turns on the LCD display, after it's been turned off with noDisplay().
This will restore the text (and cursor) that was on the display.
Syntax:
lcd.display()
Parameters:
void setup() {
lcd.begin(16,2);
lcd.print(
“hello, world!
”);
}
void loop() {
lcd.noDisplay();
delay(500);
lcd.display();
}
Description:
Syntax:
Page 77
lcd.noDisplay()
Parameters:
}
void loop() {
lcd.noDisplay();
delay(500);
lcd.display();
}
Description:
Scrolls the contents of the display (text and cursor) one space to the left.
Syntax:
lcd.scrollDisplayLeft()
Parameters:
void setup() {
lcd.begin(16,2);
lcd.print(“hello, world!
”);
}
void loop() {
lcd.scrollDisplayLeft();
delay(150);
}
Description:
Page 78
Scrolls the contents of the display (text and cursor) one space to the right.
Syntax:
lcd.scrollDisplayRight()
Parameters:
void setup() {
lcd.begin(16,2);
lcd.print(
“hello, world!
”);
}
void loop() {
lcd.scrollDisplayRight();
delay(150);
}
Description:
This causes each character output to the display to push previous characters
over by one space.
If the current text direction is left-to-right (the default), the display scrolls to the
left; if the current direction is right-to-left, the display scrolls to the right.
This has the effect of outputting each new character to the same location on the
LCD.
Syntax:
lcd.autoscroll()
Parameters:
Page 79
LiguidCrystal lcd
= new LiquidCrystal(11,10,3,2,1,0);
void setup() {
lcd.begin(16,2);
lcd.autoscroll();
lcd.print(“hello, world!
”);
}
Description:
Syntax:
lcd.noAutoscroll()
Parameters:
void setup() {
lcd.begin(16,2);
lcd.noAutoscroll();
lcd.print(“hello, world!
”);
}
Description:
Set the direction for text written to the LCD to left-to-right, the default.
This means that subsequent characters written to the display will go from left to
right, but does not affect previously-output text.
Syntax:
lcd.leftToRight()
Parameters:
Page 80
lcd: a variable of type LiquidCrystal
void setup() {
lcd.begin(16,2);
lcd.leftToRight();
}
Description:
This means that subsequent characters written to the display will go from right to
left, but does not affect previously-output text.
Syntax:
lcd.rightToLeft()
Parameters:
void setup() {
lcd.begin(16,2);
lcd.rightToLeft();
}
Description:
Create a custom character for use on the LCD. Up to 8 characters of 5x8 pixels
are supported.
Page 81
Syntax:
lcd.createChar(num, data)
Parameters:
lcd: a variable of type LiquidCrystal
Interface the LCD display to the Arduino Uno Board using 4-bit mode and write a simple
program to display the number of seconds since the reset of the Arduino board.
create an LCD object with -4bit mode and set interface pins
LiquidCrystal lcd =new LiquidCrystal(this, 10, 11, 3, 2, 1, 0);
Page 82