0% found this document useful (0 votes)
31 views127 pages

15-2-25 Mic

The document provides an overview of advanced microcontrollers, specifically focusing on Arduino and its applications. It details the architecture, features, and programming of the ATmega328P microcontroller used in Arduino boards, along with the Arduino IDE for coding. Additionally, it discusses various Arduino models, add-ons, and the advantages of using Arduino for electronics projects.

Uploaded by

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

15-2-25 Mic

The document provides an overview of advanced microcontrollers, specifically focusing on Arduino and its applications. It details the architecture, features, and programming of the ATmega328P microcontroller used in Arduino boards, along with the Arduino IDE for coding. Additionally, it discusses various Arduino models, add-ons, and the advantages of using Arduino for electronics projects.

Uploaded by

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

Advanced Microcontrollers &

Applications

Class: ECE- 4th Semester


Academic session: Jan-May,
2025
(SECTION-B)
Open Source Embedded
Development Board
(Arduino)
What is a Microcontroller
(µC, MCU)
• Computer on a single integrated chip
– Processor (CPU)
– Memory (RAM / ROM / Flash)
– I/O ports (USB, I2C, SPI, ADC)
• Common microcontroller families:
– Intel: 4004, 8008, etc.
– Atmel: AT andAVR
– Microchip: PIC
– ARM: (multiple manufacturers)
• Used in:
– Cellphones,
– Toys
– Household appliances
– Cars
– Cameras
The ATmega328P Microcontroller
(used by the Arduino)
• AVR 8-bit RISC architecture
• Available in DIP package
• Up to 20 MHz clock
• 32kB flash memory
• 1 kB SRAM
• 23 programmable I/O
channels
• Six 10-bit ADC inputs
• Three timers/counters
• Six PWM outputs
What is Arduino?
• Arduino is a popular “open source” single board
microcontroller.
• It is designed to make the process of using
electronics in multidisciplinary projects more
accessible.

This idea began in Italy and its initial


purpose was to make STUDENTdesign
projects more affordable than other
prototyping projects at the time.
Introduction to Arduino
• Arduino is a microcontroller based kit
• Purchased from the vendor or can be
made at home using the components.
• It is basically used in communications and
in controlling or operating many devices.
• It was founded by Massimo Banzi and
David Cuartielles in 2005.
Introduction to Arduino
• Arduino is an open source platform used for building
electronics projects.

• Arduino consists of both a physical programmable circuit


board or microcontroller and a software, IDE (Integrated
Development Environment) that runs on the computer.

• It is used to write and upload computer code to the physical


board.

• Arduino boards are equipped with sets of digital and analog


input/output pins, USB connection which is used for loading
programs from computers, power jack, reset button etc.
Arduino IDE Features
• It is an open source software.
• Easy to write code and upload it to the
physical board.
• Easy to learn programming language with its
inbuilt functions.
• Runs on windows, Mac OS and Linux.
• This software can be used with any Arduino
board.
Features of Arduino
• Arduino boards are able to read analog or digital input signals from different
sensors and turn it into an output such as activating a motor, turning LED
on/off, connect to the cloud and many other actions.

• You can control your board functions by sending a set of instructions to the
microcontroller on the board via Arduino IDE (referred to as uploading
software).

• Unlike most previous programmable circuit boards, Arduino does not need
an extra piece of hardware (called a programmer) in order to load a new
code onto the board. You can simply use a USB cable.

• Additionally, the Arduino IDE uses a simplified version of C++, making it


easier to learn to program.

• Finally, Arduino provides a standard form factor that breaks the functions of
the micro-controller into a more accessible package.
Reasons why Arduino is being preferred
1. It is inexpensive

2. It comes with an open source hardware feature which enables users to develop their own
kit using already available one as a reference source.

3. The Arduino software is compatible with all types of operating systems like Windows,
Linux, and Macintosh etc.

4. It also comes with open source software feature which enables experienced software
developers to use the Arduino code to merge with the existing programming language
libraries and can be extended and modified.

5. It is easy to use for beginners.

6. We can develop an Arduino based project which can be completely stand alone or projects
which involve direct communication with the software loaded in the computer.

7. It comes with an easy provision of connecting with the CPU of the computer using serial
communication over USB as it contains built in power and reset circuitry.
The Many Flavors of Arduino

• Arduino Uno
• Arduino Leonardo
• Arduino LilyPad
• Arduino Mega
• Arduino Nano
• Arduino Mini
• Arduino Mini Pro
• Arduino BT
Arduino-like Systems

• Cortino (ARM)
• Xduino (ARM)
• LeafLabs Maple
(ARM)
• BeagleBoard (Linux)
• Wiring Board
(Arduino
predecessor)
Arduino Add-ons (Shields)
• TFT Touch Screen
• Data logger
• Motor/Servo shield
• Ethernet shield
• Audio wave shield
• Cellular/GSM shield
• WiFi shield
• ...many more
Where to Get an Arduino Board

• Purchase from online vendor (available


worldwide)
– Sparkfun
– Adafruit
– DFRobot
• ... or build your own
– PC board
– Solderless breadboard http://itp.nyu.edu/physcomp/Tutorials/ArduinoBreadboard
Arduino Uno
Original Arduino with RS-232
Other Hardware Choices-Sheilds
 Xbee Shield
The Xbee shield allows an Arduino board to communicate wirelessly using Zigbee.
The module can communicate up to 100 feet indoors or 300 feet outdoors (with line-of-
sight).
 Adafruit Servo/Stepper/DC Motor shield
A shield that can control 2 hobby servos and up to 2 unipolar/bipolar stepper
motors or 4 bi-directional DC motors.
 Battery Shield
A shield from Liquidware that connects to the back of the Arduino, with a USB-
rechargable lithium ion battery that can power an Arduino for 14-28 hours depending on the
circuit
 Liquidware TouchShield
OLED touch screen shield.
Continue……………
 Adafruit Wave shield
Plays any size audio files from an SD memory card for music, effects and interactive
sound art

 Adafruit GPS & Datalogging shield


Connects up a GPS module and can log location, time/date as well as sensor data to an
SD memory flash card.

 Adafruit XPort/Ethernet shield


Allows use of an XPort module for connecting to the Internet as a client or server.
Continue…
 Liquidware TouchShield
OLED touch screen shield.
 Adafruit Servo/Stepper/DC Motor shield
A shield that can control 2 hobby servos and up to 2
unipolar/bipolar stepper motors or 4 bi-directional DC motors.
Arduino on breadboard
Basic Arduino UNO board
(Hardware)
Arduino UNO board with Atmega328
Microcontroller
Basic Arduino UNO board (Hardware)

1 Power USB connector.


2 Power port (Barrel Jack).
3 Voltage Regulator.
4 Crystal oscillator.
5 Reset switch.
6,7,8,9 Pins (3.3,5 GND, Vin)
10 Analog input pins.
11 Main Microcontroller.
12 ICSP Pin.
13 Power LED Indicator
14 Tx and Rx LEDs
15 Digital I/O pins.
16 AREF.
Block Diagram of Arduino
Digital Pins
 In addition to the specific functions listed below, the
digital pins on an Arduino board can be used for
general purpose input and output via the pinMode(),
digitalRead(), and digitalWrite() commands. Each pin
has an internal pull-up resistor which can be turned on
and off using digitalWrite() (write value of HIGH or
LOW, respectively) when the pin is configured as an
input. The maximum current per pin is 40 mA.
 Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL
serial data. On the Arduino Diecimila, these pins are connected to the
corresponding pins of the FTDI USB-to-TTL Serial chip.

 External Interrupts: 2 and 3. These pins can be configured to trigger an


interrupt on a low value, a rising or falling edge, or a change in value. See
the attachInterrupt() function fordetails.

 PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the
analogWrite() function. On boards with an ATmega8, PWM output is
available only on pins 9, 10, and 11.

 Reset: 7. (Arduino BT-only) Connected to the reset line of the bluetooth


module.

 SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI


communication, which, although provided by the underlying hardware. It
allow serial communication with another interface by connecting it serially.

 LED: 13. There is a built-in LED connected to digital pin 13. When the pin is
HIGH value, the LED is on, when the pin is LOW, it's off.
Analog Pins
In addition to the specific functions listed below, the
analog input pins support 10-bit analog-to-digital conversion
(ADC) using the analogRead() function.

Most of the analog inputs can also be used as digital pins. On


board, analog input 0 can be used as digital pin 14 and similarly
analog input 5 as digital pin 19. Analog inputs 6 and 7 (present
on the Mini and BT) cannot be used asdigital pins.

 I2C: 4 (SDA) and 5 (SCL). Support I2C (TWI) communication


using the Wire library
Power Pins
 VIN (sometimes labelled "9V"). The input voltage to the Arduino board
when it's using an external power source (as opposed to 5 volts from the USB
connection or other regulated power source). You can supply voltage
through this pin, or, if supplying voltage via the power jack, access it through
this pin. Note that different boards accept different input voltages ranges.

 5V. The regulated power supply used to power the microcontroller and
other components on the board. This can come either from VIN via an on-
board regulator, or besupplied by USB or another regulated 5V supply.

 3V3. A 3.3 volt supply generated by the on- board FTDI chip.

 GND. Ground pins.


Other Pins
 AREF. Reference voltage for the analog inputs. It
provide the analog reference voltage for analog to
digital conversion

 Reset. Bring this line LOW to reset the


microcontroller.
Atmega328 Microcontroller and its pin
mapping with Arduino board pins
Atmega8 Microcontroller and its pin mapping with Arduino board pins
Function of Each block
 USB Plug: By using this plug we can download hex file of
our program by connecting it with PC. It also provide
supply to arduino board. This USB plug is connected with
FTDI Chip internally

 FTDI Chip: This chip is nothing but voltage level converter


chip. This chip is used to convert USB voltage level to TTL
level and vice versa.

 Digital I/O and PWM section: This section is used as for


general purpose input output usage. By using this section we
can perform digital input and output functions. In this
section some pins are also used as PWM output pins. It is
used for PWM based application like servo motors.
Continue…
 Serial Tx and Rx Section: These two pins are used for serial communication
in arduino. It is internally connected with USB plug through FTDI chip.

 Power Supply: Power supply section provide different voltage level to different
part of arduino board. This part contain bridge rectifier and voltage regulator.

 AVR Atmega CPU: This block is the heart of the controller. Generally Atmega
8, Atmega 16, Atmega 32, Atmega 328 controller are used in arduino board. This
block execute all the fuctions that written in arduinoprogram.

 SPI Interface section: This section is used for serial peripheral interfacing.

 Power Pins section: This section include various voltage level


pins including ground pins.

 Analog input section: We know that Atmega 8 CPU has inbuilt 6 channel 10
– bit ADC. This ADC can convert analog data from analog pin into digital. So,
for taking analog value for digital conversion we have to use this section.
Circuit Diagram of Arduino
Arduino Architecture
• Based on Harvard architecture where the program code and
program data have separate memory.

• It consists of two memories- Program memory and the data


memory.

• The code is stored in the flash program memory, whereas the


data is stored in the data memory.

• The Atmega328 has 32 KB of flash memory for storing code (of


which 0.5 KB is used for the bootloader), 2 KB of SRAM and 1
KB of EEPROM

• Operates with a clock speed of 16MHz.


Arduino Architecture
Features of the Arduino UNO:

• Microcontroller: ATmega328
• 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: 40 mA
• DC Current for 3.3V Pin: 50 mA
• Flash Memory: 32 KB of which 0.5 KB used by bootloader
• SRAM: 2 KB (ATmega328)
• EEPROM: 1 KB (ATmega328)
• Clock Speed: 16 MHz
Arduino IDE ( Software)

• A program written with the IDE for Arduino is


called a sketch.

• The IDE enables to write and edit code and convert


this code into instructions that Arduino hardware
understands. The IDE also transfers those
instructions to the Arduino board (a process called
as uploading).
Arduino IDE (Software)
• The Arduino IDE supports the languages C and C++
using special rules of code structuring.

• It consists of only two functions, setup and loop.

• The setup function is used to initialize variables, input


and output pin modes and other libraries needed in the
sketch.

• After setup has been called, function loop is executed


repeatedly in the main program. It controls the board until
the board is powered off or reset.
How to program an Arduino?

• Programs can be directly loaded to the device without requiring any


hardware programmer to burn the program.

• 0.5KB of Bootloader- allows the program to be burned into the circuit.

• It is the first program which executes when a device is connected to a power


supply.

• All we have to do is to download the Arduino software and writing the


code.
Arduino IDE (Software)
• Series of menus like the
File, Edit, Tools menu
• Buttons like verify,
upload, new, open, save,
serial monitor.
• Text editor to write the
code
• Text console and
Message area which
displays the output and
the feedback like
showing the errors
Arduino IDE (Software)
Steps to program an Arduino
•Programs written in Arduino are known as sketches. A basic sketch
consists of 3 parts
1. Declaration of Variables
2. Initialization: It is written in the setup () function.
3. Control code: It is written in the loop () function

•The sketch is saved with .ino extension. Any operations like verifying,
opening a sketch, saving a sketch can be done using the buttons on the
toolbar or using the tool menu.
•The sketch should be stored in the sketchbook directory.
•Choose the proper board from the tools menu and the serial port
numbers.
•Click on the upload button or choose upload from the tools menu. Thus
the code is uploaded by the bootloader onto the microcontroller.
Board Type
Serial Port / COM Port
Few of basic Adruino functions are:

• digitalRead(pin): Reads the digital value at the given


pin.
• digitalWrite(pin, value): Writes the digital value to the
given pin.
• pinMode(pin, mode): Sets the pin to input or output
mode.
• analogRead(pin): Reads and returns the value.
• analogWrite(pin, value): Writes the value to that pin.
• serial.begin(baud rate): Sets the beginning of serial
communication by setting the bit rate.
Serial Communication - Writing
IMPORTANT: • Serial.begin(baud)
USB serial
communication is Initialize serial port for communication (and sets baud
shared with rate) Note: Serial.end() command
Arduino pins 0 Example: is usually unnecessary, unless you
and 1 (RX/TX) need to use pins 0 & 1
– Se ri al . beg in( 960 0) ; // 9600 baud

Format can be:• Serial.print(val), Serial.print(val,fmt)


BIN, HEX, OCT, Prints data to the serial port
or an integer
specifying the
Examples:
number of digits – Serial.print(“Hi”); // p r i n t a s t r i n g
to display – Serial.print(78); // works with numbers, too
– S e r i a l.p r i n t (va r i abl e ) ; // works with v a r i a b l e s
– S e r i a l . p r i n t( 7 8 , B I N ) ; // w i l l p r i n t 1001110

• Serial.println(val)
Same as S e r i a l . p r i n t ( ) , but with line-feed
Activity 1: LED Blink
• Load the “Blink” example
(FileExamplesBasicsBlink)
void setup() {
Use pin 13 as digital output // i n i t i a l i z e the d i g i t a l pin as an output.
// Pin 13 has an LED connected on most Arduino boards:
pinMode(13, OUTPUT);
Set output high (+5V) }

void loop() {
d i g i t a l W r i t e ( 13, HIGH); // s et the LED on
Wait 1000 milliseconds delay(1000); // wait f o r a second
d i g i t a l W r i t e ( 13, LOW); // set the LED o f f
delay(1000); // wait f o r a second
Set output low (0V) }

• Compile, then upload the program


• Congratulations! you are now blinkers!
Now connect your own LED
LED:

Notes:
• Resistor is needed to limit current
• Resistor and LED may be
interchanged
(but polarity of LED is important)
http://www.wikipedia.org/ • Pin 13 is special: has built-in
resistor and LED
• Change program and upload
Example: Using a Solderless
Breadboard
Comments
• Comments can be anywhere
• Comments created with // or /* and */
• // is used for single linecomment.
• /* */ is used for multiline
comments
• Comments do not affect code
• You may not need comments, but
think about the community!
Programming Symbols
/ / - Single line comment
/* */ - Multiline comment
{ } –used to define a block of code that starts andends.
; - used to define the end of a line of code.
Numeric Data Type in Arduino Programming
Types of operators
• Arithmetic Operators
• Comparison Operators
• Boolean Operators
• Bitwise Operators
• Compound Operators
Arithmetic Operators
Comparison Operators
Boolean Operators
Bitwise Operators
Compound Operators
Arduino programming Language
Fade

Fade

This example shows how to fade an LED on pin 9 using the analogWrite()
function.

The analogWrite() function uses PWM, so if you want to change the pin you're
using, be sure to use another PWM capable pin. On most Arduino, the PWM pins
are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);

// change the brightness for next time through the loop:


brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:


if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
PWM ( Pulse Width Modulation)
The duty cycle of the pulse is shown below:

to: It is the duration of the signal when the signal is HIGH.


tc: It is the total duration of the signal as the sum of HIGH and LOW.
Duty cycle of a PWM wave
The duty cycle is the ratio of the pulse width to the total width of a signal.
PWM technique with various duty cycles and average voltages.
Analog I/O interfacing
The main differences between analogRead() and
analogWrite() are listed below:

• The analogRead() is used to read the analog


value, while analogWrite() function is used to
write the PWM value.

• The value of analogRead() ranges from 0 to 1023,


while analogWrite() ranges from 0 to 255.
• The value associated with the analog signal on the digital
pins is from 0 to 255. It means 256 levels of values.

• The maximum voltage read by the Arduino is 5V.

• We can determine the output PWM voltage by using the


below formula:

PWM voltage = ( Duty cycle/ 256) x 5V


Analog input, analog output, serial
output

Reads an analog input pin, maps the


result to a range from 0 to 255 and
uses the result to set the pulsewidth
modulation (PWM) of an output pin.
Also prints the results to the serial
monitor.
Keypad Interfacing
Circuit Connection
Program
Interfacing of 16x2 LCD (Liquid Crystal Display)
with Arduino

Pin 1

Pin 16
Display 32 Characters
#include
<LiquidCrystal.h>

The library works with in


either 4- bit or 8-bit mode
(i.e. using 4 or 8 data
lines in addition to the rs,
enable, and, optionally,
the r/w control lines).
Circuit Connection
Circuit Connection
LCD Interfacing Program
Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are
compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them
by the 16-pin interface. This sketch prints "Hello World!" to the LCD and shows the time.
The circuit:

* 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 ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
LCD Interfacing Program
Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are
compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them
by the 16-pin interface. This sketch prints "Hello World!" to the LCD and shows the time.
The circuit:

* 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 ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
// include the library code: void loop()
#include <LiquidCrystal.h> {
// set the cursor to column 0, line 1
// initialize the library with the numbers
// (note: line 1 is the second row, since
of the interface pins
counting begins with 0):

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); lcd.setCursor(0, 1);

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!");
}
Circuit
Diagram of
LCD
Interfacing
with
Arduino
Communication Protocols

• Communication protocols are defined to


achieve data exchange.
• Each protocol can be categorized into one of
the two categories:
– Serial
OR
– Parallel
• Parallel Communication:
 Useful in shorter distances ( upto several meters).
 Example Parallel connection between Arduino and peripherals
via I/O ports.
 Long distance communication is not possible.
Advantages and Drawbacks of Parallel
Communication

• Faster than serial, easy to implement .


• Parallel interfaces transfer multiple bits at the same
time.
• Disadvantages:
• Requires many input/output (I/O) ports and lines.
Serial Communication
• Sent and receive data through stream of bits.
• This stream of bits is governed by set of rules called
as protocol.
• It is a set of rules, which must be applied such that
the devices can correctly interpret data they mutually
exchange.
• Arduino automatically takes care of this, so that the
work of the programmer/user is reduced to simple
write (data to be sent) and read (received data).
Types of Serial communication
• Synchronous :
Devices that are synchronized use the
same clock and their timing is in
synchronization with each other.
• Asynchronous:
Devices that are asynchronous have their
own clocks and are triggered by the output of
the previous state.
UART (Universal Asynchronous Receiver
Transmitter) module is asynchronous.
• The asynchronous serial protocol has a number of built-in
rules. These rules are nothing but mechanisms that help
ensure robust and error-free data transfers.

 Synchronization bits:
Two or three bits transferred with each packet of data.
They are start bit and stop bit.
The start bit is always indicated by an idle data line going from
1 to 0, while the stop bit(s) will transition back to the idle state
by holding the line at 1.
 Data bits:

The amount of data in each packet can be set to any size from
5 to 9 bits.
Certainly, the standard data size is your basic 8-bit (byte), but
other sizes have their uses.
A 7-bit data packet can be more efficient than 8, especially if
you are just transferring 7-bit ASCII characters.
Parity bits:

The user can select whether there should be


a parity bit or not, and if yes, whether the
parity should be odd or even. The parity bit
is 0 if the number of 1’s among the data bits
is even. Odd parity is just the opposite
 Baud rate:

The term baud rate denotes number of bits transferred per


second (bps).

It is usually required by the protocol that each


byte is transferred along with several control
bits.
Serial communication Protocols
I2C (Inter- Integrated Circuit) :
• Inter-integrated circuit (I2C) is a system for serial
data exchange between the microcontrollers and
specialized integrated circuits of a new
generation.
• Used when the distance between them is short
(receiver and transmitter are usually on the same
printed board).
• Connection is established via two conductors.
One is used for data transfer and the other is
used for synchronization (clock signal).
The address of I2C is 7 bits long. Theoretically allows 128 I2C addresses, however
some addresses are reserved for special purposes, thus only 112 addresses are
available with 7 bit scheme.
If 10 bit addressing, 1024(1008) devices…
• One device is always a master. It performs addressing of one slave chip before the communication
starts.

• Baud rate is usually 100 Kb/sec (standard mode) or 10 Kb/sec (slow baud rate mode). Systems with the
baud rate of 3.4 Mb/sec have recently appeared.

• The distance between devices, which communicate over an I2C bus is limited to several meters.
Arduino board I2C pins
• The I2C bus consists of two signals − SCL and
SDA.
• SCL is the clock signal, and SDA is the data
signal.
• Master always generates the clock signal. Some
slave devices may force the clock low at times to
delay the master sending more data (or to require
more time to prepare data before the master
attempts to clock it out). This is known as “clock
stretching”.
• Following are the pins for Arduino boards −
• Uno, Pro Mini {A4 (SDA), A5 (SCL)}
Arduino I2C Modes
• Two modes - master code and slave code -
to connect two Arduino boards using I2C.

• Master Transmitter / Slave Receiver


• Master Receiver / Slave Transmitter
Master to Slave
Master Transmitter / Slave Receiver
Slave to Master
Slave Transmitter / Master Receiver
Various Functions used in I2C
Master Transmitter / Slave Receiver
• Master Transmitter:
• The following functions are used to initialize the Wire library and join
the I2C bus as a master or slave. This is normally called only once.
• Wire.begin(address) − Address is the 7-bit slave address in our
case as the master is not specified and it will join the bus as a
master.
• Wire.beginTransmission(address) − Begin a transmission to the
I2C slave device with the given address.
• Wire.write(value) − Queues bytes for transmission from a master to
slave device (in-between calls to beginTransmission() and
endTransmission()).
• Wire.endTransmission() − Ends a transmission to a slave device
that was begun by beginTransmission() and transmits the bytes that
were queued by Wire.write().
Slave receiver
The following functions are used −

• Wire.begin(address) − Address is the 7-bit slave address.

• Wire.onReceive(received data handler) − Function to be called


when a slave device receives data from the master.

• Wire.available() − Returns the number of bytes available for


retrieval with Wire.read().This should be called inside the
Wire.onReceive() handler.
Master Receiver / Slave Transmitter
Master Receiver

The Master, is programmed to request, and then read bytes of data that
are sent from the uniquely addressed Slave Arduino.

The following function is used −

Wire.requestFrom(address,number of bytes) − Used by the master


to request bytes from a slave device. The bytes may then be retrieved
with the functions wire.available() and wire.read() functions.
Example
#include <Wire.h> //include wire library
void setup() //this will run only once
{
Wire.begin(); // join i2c bus as master }
short age = 0; // short storage size is 2 bytes (value range -32768 to 32767)
void loop()
{ Wire.beginTransmission(2); // transmit to device #2
Wire.write("age is = ");
Wire.write(age); // sends one byte
Wire.endTransmission(); // stop transmitting
delay(1000);
}
Example
#include <Wire.h> //include wire library
#DEFINE SLAVEADDR 2
void setup()
{ //this will run only once
Wire.begin(2); // join i2c bus with address #2
Wire.onReceive(receiveEvent); // call receiveEvent when the master send any thing
Serial.begin(9600); // start serial for output to print what we receive }
void loop()
{ delay(250); } //-----this function will execute whenever data is received from master-----
//
void receiveEvent(int howMany)
{ while (Wire.available()>1) // loop through all but the last
{ char c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character }
}
Serial Peripheral Interface (SPI)
A Serial Peripheral Interface (SPI) bus is a system for serial
communication, which uses up to four conductors, commonly three.

One conductor is used for data receiving,


One for data sending,
One for synchronization and
One alternatively for selecting a device to communicate with.

It is a full duplex connection: means that the data is sent and received
simultaneously.
The maximum baud rate is higher than that in the I2C communication
system.
Transmission modes
Simplex Mode Half Duplex Mode

Full-Duplex Mode
SPI pins on Arduino Board
SPI uses the following four wires −

SCK − This is the serial clock driven by the master.


MOSI − This is the master output / slave input driven by the master.
MISO − This is the master input / slave output driven by the master.
SS/CS − This is the slave-selection wire.
Schematic and Direction of Data Transfer

SCK- Serial Clock

MASTER MOSI- Master out Slave In


MICROCONTROLLER SLAVE
(ARDUINO UNO) MISO-Master In Slave Out
DEVICE

SS- Slave Select


HOW TO USE AN ARDUINO WITH SPI

• Pins 10-13 are usually used, but there


are also MOSI, MISO, and SCLK pins
on the ICSP header (near the
ATMEGA chip).

• The MOSI, MISO, and SCLK on pins


11-13 and on the ICSP header are
one and the same, so using the ICSP
header doesn’t free up pins 11-13 for
other purposes.
CONNECTING A MASTER DEVICE TO A
MULTIPLE SLAVE DEVICES
SPI Modes of Operation
Depending upon Clock Polarity (CPOL) and Clock
Phase (CPHA) values.

1. Mode0
2. Mode1
3. Mode2
4. Mode3
• Mode 0 (the default) − Clock is normally low (CPOL = 0),
and the data is sampled on the transition from low to high
(leading edge) (CPHA = 0).
• Mode 1 − Clock is normally low (CPOL = 0), and the
data is sampled on the transition from high to low
(trailing edge) (CPHA = 1)
• Mode 2 − Clock is normally high (CPOL = 1), and the
data is sampled on the transition from high to low
(leading edge) (CPHA = 0).
• Mode 3 − Clock is normally high (CPOL = 1), and the data is
sampled on the transition from low to high (trailing edge) (CPHA = 1).
Two Arduino UNO Board connection as
Master and Slave
• (SS) : pin 10
• (MOSI) : pin 11
• (MISO) : pin 12
• (SCK) : pin 13

The ground is common.


Functions used in SPI
• include the SPI.h library

• SPI.begin() − Initializes the SPI bus by setting SCK, MOSI, and SS


to outputs, pulling SCK and MOSI low, and SS high.

• SPI.setClockDivider(divider) − To set the SPI clock divider relative


to the system clock.

• The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to


one-quarter of the frequency of the system clock (5 MHz for the
boards at 20 MHz).
• Divider− It could be (SPI_CLOCK_DIV2,
SPI_CLOCK_DIV4,SPI_CLOCK_DIV8,SPI_CLOCK_DIV16,SPI_CLOCK_DIV32,
SPI_CLOCK_DIV64,SPI_CLOCK_DIV128).

• SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive:


the received data is returned in receivedVal.

• SPI.beginTransaction(SPISettings(speedMaximum, dataOrder, dataMode)) −


speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST),
dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3).
Comparison Between IIC and SPI
12C - Inter Integrated Circuit SPI - Serial Peripheral Interface Bus
Parameters
Bus {Philips-1982) {Motorola-1979}
Numbers of Wires Only Two wires Four Wire

Communication Half Duplex Half Duplex / Full Duplex


Suitable for Multiple Master Multiple
Configuration Suitable for Single Master Multiple Slave
Slave
Speed Slower {400Kbps Majority} Faster {10Mbps Majority}

Start & Stop bits Required Not required

Acknowledgment after
Required Not required
data transfer

Redundant data Required {Start + Stop + Address} Not required

Cost Low cost {Only two wire configuration} Costly {Minimum Four wire configuration}

IO Constraint Pull Resistor Not required

Addressing 7 bits addressing Chip Select

Power consumption Bit high {Pull Up resistor} Low

Plug & Play Yes No


SPI as master (example)
#include <SPI.h>
void setup (void)
{ Serial.begin(115200); //set baud rate to 115200 for usart
digitalWrite(SS, HIGH); // disable Slave Select
SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8);//divide the clock by 8 }
void loop (void)
{
char c; digitalWrite(SS, LOW); // enable Slave Select
// send test string
for (const char * p = "Hello, world!\r" ; c = *p; p++)
{
SPI.transfer (c);
Serial.print(c);
}
digitalWrite(SS, HIGH); // disable Slave Select
delay(2000);
}

You might also like