You are on page 1of 178

GOKARAJU RANGARAJU INSTITUTE OF ENGINEERING & TECHNOLOGY

(DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING)

(Autonomous)

(Affiliated to Jawaharlal Nehru Technological University)


Hyderabad 500 090

M.Tech. Embedded Systems I Year I semester

MICROCONTROLLERS LAB

Manual & Record Book


Prepared by
N.OME
Asst.Professor, ECE
GRIET, HYD
Email ID:omenerella@gmail.com
GOKARAJU RANGARAJU INSTITUTE OF ENGINEERING & TECHNOLOGY

(DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING)

(Autonomous)

(Affiliated to Jawaharlal Nehru Technological University)


Hyderabad 500 090

M.Tech. Embedded Systems I Year I semester

MICROCONTROLLERS LAB

Manual &Record Book

Name:
Reg. No.:
Branch:
Class:

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


CERTIFICATE

This is to certify that it is a bonafide record of practical

work done by Mr. /Ms.______________________________,

Reg.No.___________________ in the“Microcontrollers

LAB”in__ semester of ___ year during 20__ -20___.

External Examiner LAB Incharge

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


MICROCONTROLLERS LABORATORY

M.Tech(ES) I Year –I semester


Course code: L/P/C: 0/4/2

Note:

• Minimum of 10 experiments have to be conducted.


• Experiments to be carried out on ARM based board (Arduino Due-ATMEL SAM3X8E
ARM Cortex –M3 CPU) or equivalent using Embedded C Language on Arduino IDE or
Equivalent.

List of Experiments:

1.Program to configure and control General Purpose Input/Output (GPIO)port pins of ARM.

2.Program for UART-Echo test.

3.Program to get analog input from Temperature sensor and display the temperature value on PC.

4.Progam to interface LCD with ARM for displaying a message on it.

5. Program to implement RFID based access control system.

6.Program to Develop Bluetooth based monitoring and appliance control System.

7.Program for wireless based data transfer using Zigbee.

8.Program for generation of PWM signal.

9.Program to implement the Embedded Web Server using Ethernet module .

10.Program for reading and writing of a file on SD card.

11.Program to Interface SD card module with ARM to produce Audio output on speaker.

12.Program to interface USB based mouse/keyboard with ARM.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


HARDWARE AND SOFTWARE USED IN THIS LAB

HARDWARE:

1.HP Laptops:CORE I3-5005U(5GEN)HP,4GB RAM,1TB hard Disk, Windows 10-64 bit OS

2.Arduino Due Boards-ARM based Microcontroller(ATMEL-SAM3X8E)

3.Interfacing modules

i) LEDS and Switches Shields ii) LCD Shields iii) RFID Raders & TAGS

iv) Ethernet Shields-(Audio and SD card) v) Bluetooth Modules vi) Xbee Shields

vii) Sensors viii) Actuators

SOFTWARE: ARDUINO IDE-1.6.12

ARDUINO IDE:

The open-source Arduino Software (IDE) makes it easy to write code and upload it to the board.
It runs on Windows, Mac OS X, and Linux. The environment is written in Java and based on
Processing and other open-source software. Arduino is an open-source electronics platform
based on easy-to-use hardware and software. Arduino boards are able to read inputs - light on a
sensor, a finger on a button, or a Twitter message - and turn it into an output - activating a motor,
turning on an LED, publishing something online. You can tell your board what to do by sending
a set of instructions to the microcontroller on the board. To do so you use the Arduino
programming language (based on Wiring), and the Arduino Software (IDE), based
on Processing.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


S.No Name of the Experiment Date of Faculty Remarks
completion signature

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
CONTENTS

Introduction to Arduino Due 1


Arduino Programming 9
Introduction To Atmel SAM3x8E 20
Digital IO 25
ARM Programming: Parallel IO 32
Serial communication 41
ARM Serial Programming: UART 45
Arduino Timers and Interrupt Functions 57
Analog Inputs 67
LCD 73
RFID 79
Bluetooth 89
Zigbee
93
Analog Outputs 101
Serial to Peripheral Interface (SPI) Protocol 107
Ethernet Basics
112
Embedded Web server 115
SD card Module 131
Audio 137
USB Host 141
Exercises 147

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


MICROCONTROLLERS LAB

The hardware platform on which the Microcontrollers Lab will be based on the Arduino Due
board.The Arduino Due is a microcontroller board based on the AtmelSAM3X8E ARM Cortex-
M3 CPU. It is the first Arduino board based on a 32-bit ARM core microcontroller. The basic
features of the Arduino Due are:

• 54 digital input/output pins (of which 12 can be used as PWM outputs)


• 12 analog inputs
• 4 UARTs(hardware serial ports)
• 84 MHz clock
• USB OTG(On the Go) capable connection
• 2 DACs(digital to analog)
• 2 TWI(Two wire interface)
• Power jack
• SPI(Serial Peripheral Interface) header

ARDUINO DUE BOARD

The board contains everything needed to support the microcontroller; simply connect it to a
computer with a micro-USB cable or power it with a AC-to-DC adapter or battery to get started.
The Due is compatible with all Arduino shields that work at 3.3V and are compliant with the 1.0
Arduino pinout. Unlike other Arduino boards, the Arduino Due board runs at 3.3V. The
maximum voltage that the I/O pins can tolerate is 3.3V.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 1
ARM Core benefits
The Due has a 32-bit ARM core that can outperform typical 8-bit microcontroller boards. The
most significant differences are:
• A 32-bit core, that allows operations on 4 bytes wide data within a single CPU clock.
• CPU Clock at 84Mhz.
• 96 KBytes of SRAM.
• 512 KBytes of Flash memory for code.
• a DMA controller, that can relieve the CPU from doing memory intensive tasks.
Features of Arduino Due

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 2
Power
The Arduino Due can be powered via the USB connector or with an external power supply. The
power source is selected automatically.
External (non-USB) power can come either from an AC-to-DC adapter (wall-wart) or battery.
The adapter can be connected by plugging a 2.1mm center-positive plug into the board's power
jack. Leads from a battery can be inserted in the Gnd and Vin pin headers of the POWER
connector.
The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V,
however, the 5V pin may supply less than five volts and the board may be unstable. If using
more than 12V, the voltage regulator may overheat and damage the board. The recommended
range is 7 to 12 volts.
The power pins are as follows:

VIN. 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.

5V. This pin outputs a regulated 5V from the regulator on the board. The board can be supplied
with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of
the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can
damage your board. We don't advise it.

3.3V. A 3.3 volt supply generated by the on-board regulator. Maximum current draw is 800 mA.
This regulator also provides the power supply to the SAM3X microcontroller.

GND. Ground pins.

IOREF. This pin on the Arduino board provides the voltage reference with which the
microcontroller operates. A properly configured shield can read the IOREF pin voltage and
select the appropriate power source or enable voltage translators on the outputs for working with
the 5V or 3.3V.

Memory
The SAM3X has 512 KB (2 blocks of 256 KB) of flash memory for storing code. The bootloader
is preburned in factory from Atmel and is stored in a dedicated ROM memory. The available
SRAM is 96 KB in two contiguous bank of 64 KB and 32 KB. All the available memory (Flash,
RAM and ROM) can be accessed directly as a flat addressing space.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 3
It is possible to erase the Flash memory of the SAM3X with the onboard erase button. This will
remove the currently loaded sketch from the MCU. To erase, press and hold the Erase button for
a few seconds while the board is powered.

Input and Output


Digital I/O: pins from 0 to 53 :Each of the 54 digital pins on the Due can be used as an input or
output, using pinMode(),digitalWrite(), and digitalRead() functions. They operate at 3.3 volts.
Each pin can provide (source) a current of 3 mA or 15 mA, depending on the pin, or receive
(sink) a current of 6 mA or 9 mA, depending on the pin. They also have an internal pull-up
resistor (disconnected by default) of 100 KOhm. In addition, some pins have specialized
functions:
Serial: 0 (RX) and 1 (TX)
Serial 1: 19 (RX) and 18 (TX)
Serial 2: 17 (RX) and 16 (TX)
Serial 3: 15 (RX) and 14 (TX)
Used to receive (RX) and transmit (TX) TTL serial data (with 3.3 V level). Pins 0 and 1
are connected to the corresponding pins of the ATmega16U2 USB-to-TTL Serial chip.
PWM: Pins 2 to 13
Provide 8-bit PWM output with the analogWrite() function. The resolution of the PWM
can be changed with the analogWriteResolution() function.
SPI: SPI header (ICSP header on other Arduino boards) These pins support SPI communication
using the SPI library. The SPI pins are broken out on the central 6-pin header, which is
physically compatible with the Uno, Leonardo and Mega2560. The SPI header can be used only
to communicate with other SPI devices, not for programming the SAM3X with the In-Circuit-
Serial-Programming technique. The SPI of the Due has also advanced features that can be used
with the Extended SPI methods for Due.
CAN: CANRX and CANTXThese pins support the CAN communication protocol but are not
not yet supported by Arduino APIs.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 4
"L" LED: 13There is a built-in LED connected to digital pin 13. When the pin is HIGH, the
LED is on, when the pin is LOW, it's off. It is also possible to dim the LED because the digital
pin 13 is also a PWM outuput.
TWI 1: 20 (SDA) and 21 (SCL)
TWI 2: SDA1 and SCL1. Support TWI communication using the Wire library.
Analog Inputs: pins from A0 to A11 The Due has 12 analog inputs, each of which can provide
12 bits of resolution (i.e. 4096 different values). By default, the resolution of the readings is set
at 10 bits, for compatibility with other Arduino boards. It is possible to change the resolution of
the ADC with analogReadResolution(). The Due’s analog inputs pins measure from ground to a
maximum value of 3.3V. Applying more then 3.3V on the Due’s pins will damage the SAM3X
chip. The analogReference() function is ignored on the Due.
The AREF pin is connected to the SAM3X analog reference pin through a resistor bridge. To use
the AREF pin, resistorBR1 must be desoldered from the PCB.

DAC1 and DAC2 These pins provides true analog outputs with 12-bits resolution (4096 levels)
with the analogWrite() function. These pins can be used to create an audio output using the
Audio library.

Other pins on the board:AREF Reference voltage for the analog inputs. Used with
analogReference().Reset Bring this line LOW to reset the microcontroller. Typically used to add
a reset button to shields which block the one on the board.

Communication: The Arduino Due has a number of facilities for communicating with a
computer, another Arduino or other microcontrollers, and different devices like phones, tablets,
cameras and so on. The SAM3X provides one hardware UART and three hardware USARTs for
TTL (3.3V) serial communication.

The Programming port is connected to an ATmega16U2, which provides a virtual COM port to
software on a connected computer (To recognize the device, Windows machines will need a .inf
file, but OSX and Linux machines will recognize the board as a COM port automatically.). The
16U2 is also connected to the SAM3X hardware UART. Serial on pins RX0 andTX0 provides
Serial-to-USB communication for programming the board through the ATmega16U2
microcontroller. The Arduino software includes a serial monitor which allows simple textual

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 5
data to be sent to and from the board. The RX and TX LEDs on the board will flash when data is
being transmitted via the ATmega16U2 chip and USB connection to the computer (but not for
serial communication on pins 0 and 1).
The Native USB port is connected to the SAM3X. It allows for serial (CDC) communication
over USB. This provides a serial connection to the Serial Monitor or other applications on your
computer. It also enables the Due to emulate a USB mouse or keyboard to an attached computer.
To use these features, see the Mouse and Keyboard library reference pages. The Native USB port
can also act as a USB host for connected peripherals such as mice, keyboards, and smart phones.
To use these features, see the USB Host reference pages. The SAM3X also supports TWI and
SPI communication. The Arduino software includes a Wire library to simplify use of the TWI
bus.

Programming
The Arduino Due can be programmed with the Arduino software. Uploading sketches to the
SAM3X is different than the AVR microcontrollers found in other Arduino boards because the
flash memory needs to be erased before being re-programmed. Upload to the chip is managed by
ROM on the SAM3X, which is run only when the chip's flash memory is empty.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 6
Either of the USB ports can be used for programming the board, though it is recommended to use
the Programming port due to the way the erasing of the chip is handled:

• Programming port: To use this port, select "Arduino Due (Programming Port)" as your board
in the Arduino IDE. Connect the Due's programming port (the one closest to the DC power jack)
to your computer. The programming port uses the 16U2 as a USB-to-serial chip connected to the
first UART of the SAM3X (RX0 and TX0). The 16U2 has two pins connected to the Reset and
Erase pins of the SAM3X. Opening and closing the Programming port connected at 1200bps
triggers a “hard erase” procedure of the SAM3X chip, activating the Erase and Reset pins on the
SAM3X before communicating with the UART. This is the recommended port for programming
the Due. It is more reliable than the "soft erase" that occurs on the Native port, and it should
work even if the main MCU has crashed.
• Native port: To use this port, select "Arduino Due (Native USB Port)" as your board in the
Arduino IDE. The Native USB port is connected directly to the SAM3X. Connect the Due's
Native USB port (the one closest to the reset button) to your computer. Opening and closing the
Native port at 1200bps triggers a 'soft erase' procedure: the flash memory is erased and the board

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 7
is restarted with the bootloader. If the MCU crashed for some reason it is likely that the soft
erase procedure won't work as this procedure happens entirely in software on the SAM3X.
Opening and closing the native port at a different baudrate will not reset the SAM3X.

Pinout Diagram

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 8
Difference from ATMEGA based boards
In general, you program and use the Due as you would other Arduino boards. There are,
however, a few important differences and functional extensions.

Voltage
The microcontroller mounted on the Arduino Due runs at 3.3V, this means that you can power
your sensors and drive your actuartors only with 3.3V. Connecting higher voltages, like the 5V
commonly used with the other Arduino boards will damage the Due.
The board can take power from the USB connectors or the DC plug. If using the DC connector,
The Arduino Due has an efficient switching voltage regulator, compliant with the USB host
specification. If the NativeUSB port is used as host by attaching a USB device to the mirco-A
usb connector, the board will provide the power to the device. When the board is used as a usb
host, external power from the DC connector is required.

Serial ports on the Due

The Arduino Due has two USB ports available. The Native USB port (which supports CDC
serial communication using the SerialUSB object) is connected directly to the SAM3X MCU.
The other USB port is the Programming port. It is connected to an ATMEL 16U2 which acts as
a USB-to-Serial converter. This Programming port is the default for uploading sketches and
communicating with the Arduino.
The USB-to-serial converter of the Programming port is connected to the first UART of the
SAM3X. It's possible to communicate over this port using the "Serial" object in the Arduino
programming language.
The USB connector of the Native port is directly connected to the USB host pins of the SAM3X.
Using the Native port enables you to use the Due as a client USB peripheral (acting as a mouse

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 9
or a keyboard connected to the computer) or as a USB host device so that devices can be
connected to the Due (like a mouse, keyboard, or an Android phone). This port can also be used
as a virtual serial port using the "SerialUSB" object in the Arduino programming language.
Automatic (Software) Reset
The SAM3X microcontroller differs from AVR microcontrollers because the flash memory
needs to be erased before being re-programmed. A manual procedure would involve holding the
erase button for a second, pressing the upload button in the IDE, then the reset button.
Because a manual erase-flash procedure is repetitive, this is managed automatically by both USB
ports, in two different ways:

USB Host
The Due has the ability to act as a USB host for peripherals connected to the SerialUSB
port. When using the Due as a host, it will be providing power to the attached device. It is
strongly recommended to use the DC power connector when acting as a host.
ADC and PWM resolutions
The Due has the ability to change its default analog read and write resolutions (10-bits and 8-
bits, respectively). It can support up to 12-bit ADC and PWM resolutions.

Arduino Programming

Click on the Arduino executable which has the Arduino logo

The following screen comes up:

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 10
The programs written for Arduino are called sketches. For the sketch to work on the Arduino
Due, there are two hardware related settings need to be done in the Arduino IDE –

• Board, Serial Port

• For selecting the board, go to the Tools tab and select Board. From the menu select
Arduino Due.

When you connect your Arduino Due to the USB port of your laptop, it will be mapped as a
serial port.

To know the serial port to which your Arduino is mapped, follow the following procedure:
Right click on My Computer
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 11
Select the Manage option

In the pop up screen for Computer Management, select the Device Manager

Expand the Ports item; the Arduino Due will appear as one of the drop down items

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 12
In the Arduino IDE, select the Serial Port as the port to which the Arduino is mapped.

The basic structure of the Arduino sketch is fairly simple and has two required functions:
void setup()
{
statements;
}
void loop()
{
statements;
}
Where setup() is the preparation, loop() is the execution. Both functions are required for
the program to work.The setup function should follow the declaration of any variables at the very
beginning of the program. It is the first function to run in the program, is run only once, and is
used to set pinMode or initialize serial communication.

The loop function follows next and includes the code to be executed continuously – reading
inputs, triggering outputs, etc. This function is the core of all Arduino programs and does the
bulk of the work.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 13
setup()
The setup() function is called once when your program starts. Use it to initialize pin
modes, or begin serial. It must be included in a program even if there are no statements to run.
void setup()
{
pinMode(pin, OUTPUT); // sets the 'pin' as output
}

loop()
After calling the setup() function, the loop() function does precisely what its name
suggests, and loops consecutively, allowing the program to change, respond, and control the
Arduino board.
void loop()
{
digitalWrite(pin, HIGH); // turns 'pin' on
delay(1000); // pauses for one second
digitalWrite(pin, LOW); // turns 'pin' off
delay(1000); // pauses for one second
}

pinMode(pin, mode)Used in voidsetup() to configure a specified pin to behave either


as an INPUT or an OUTPUT.
pinMode(pin, OUTPUT); // sets ‘pin’ to output
There are also convenient pullup resistors built into the Atmega chip that can be accessed from
software. These built-in pullup resistors are accessed in the following manner:
pinMode(pin, INPUT); // set ‘pin’ to input
digitalWrite(pin, HIGH); // turn on pullup resistors
Pullup resistors would normally be used for connecting inputs like switches. Notice in the above
example it does not convert pin to an output, it is merely a method for activating the internal
pull-ups.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 14
Pins configured as OUTPUT can provide 40 mA (milliamps) of current to other devices/circuits.
This is enough current to brightly light up an LED (don't forget the series resistor), but not
enough current to run most relays, solenoids, or motors.
Short circuits on Arduino pins and excessive current can damage or destroy the output pin, or
damage the entire Atmega chip. It is often a good idea to connect an OUTPUT pin to an external
device in series with a 470Ω or 1KΩ resistor.
digitalRead(pin)
Reads the value from a specified digital pin with the result either HIGH or LOW. The pin can be
specified as either a variable or constant (0-13).
value = digitalRead(Pin); // sets 'value' equal to the
input pin
digitalWrite(pin, value)
Outputs either logic level HIGH or LOW at (turns on or off) a specified digital pin. The pin can
be specified as either a variable or constant (0-13).
digitalWrite(pin, HIGH); // sets 'pin' to high
The following example reads a pushbutton connected to a digital input and turns on an LED
connected to a digital output when the button has been pressed:
int led = 13; // connect LED to pin 13
int pin = 7; // connect pushbutton to pin 7
int value = 0; // variable to store the read value
void setup()
{
pinMode(led, OUTPUT); // sets pin 13 as output
pinMode(pin, INPUT); // sets pin 7 as input
}
void loop()
{
value = digitalRead(pin);// sets 'value' equal to the
input pin
digitalWrite(led, value); // sets 'led' to the
button's value }

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 15
analogRead(pin)
Reads the value from a specified analog pin with a 10-bit resolution. This function only works on
the analog in pins (0-5). The resulting integer values range from 0 to 1023.
value = analogRead(pin);
// sets 'value' equal to 'pin'

Note: Analog pins unlike digital ones, do not need to be first declared as INPUT or OUTPUT.
analogWrite(pin, value)
Writes a pseudo-analog value using hardware enabled pulse width modulation (PWM) to an
output pin marked PWM. On Uno, this function works on pins 3, 5, 6, 9, 10, and 11. The value
can be specified as a variable or constant with a value from 0-255.
analogWrite(pin, value);
// writes 'value' to analog 'pin'
A value of 0 generates a steady 0 volts output at the specified pin; a value of 255 generates a
steady 5 volts output at the specified pin. For values in between 0 and 255, the pin rapidly
alternates between 0 and 5 volts - the higher the value, the more often the pin is HIGH (5 volts).
For example, a value of 64 will be 0 volts three-quarters of the time, and 5 volts one quarter of
the time; a value of 128 will be at 0 half the time and 255 half the time; and a value of 192 will
be 0 volts one quarter of the time and 5 volts three-quarters of the time.
Because this is a hardware function, the pin will generate a steady wave after a call to
analogWrite in the background until the next call to analogWrite (or a call to digitalRead or
digitalWrite on the same pin).
Note: Analog pins unlike digital ones do not need to be first declared as INPUT or OUTPUT.
The following example reads an analog value from an analog input pin, converts the value by
dividing by 4, and outputs a PWM signal on a PWM pin:
int led = 10; // LED with 220 resistor on pin 10
int pin = A0; // potentiometer on analog pin 0
int value; // value for reading
void setup(){} // no setup needed
void loop()

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 16
{
value = analogRead(pin); // sets 'value' equal to 'pin'
value /= 4; // converts 0-1023 to 0-255
analogWrite(led, value); // outputs PWM signal to led
}
delay(ms)
Pauses a program for the amount of time as specified in milliseconds, where 1000 equals
1 second.
delay(1000); // waits for one second

millis()
Returns the number of milliseconds since the Arduino board began running the current program
as an unsigned long value.
value = millis(); // sets ‘value’ equal to millis()
Note: This number will overflow (reset back to zero), after approximately 9 hours.

Serial.begin(rate)
Opens serial port and sets the baud rate for serial data transmission. The typical baud rate for
communicating with the computer is 9600 although other speeds are supported.
void setup()
{
Serial.begin(9600); // opens serial port
} // sets data rate to 9600 bps
Note: When using serial communication, digital pins 0 (RX) and 1 (TX) cannot be used at the
same time.
Serial.println(data)
Prints data to the serial port, followed by an automatic carriage return and line feed. This
command takes the same form as Serial.print(), but is easier for reading data on the Serial
Monitor.
Serial.println(analogValue); // sends the value of
// 'analogValue'

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 17
The following simple example takes a reading from analog pin0 and sends this data to the
computer every 1 second.
void setup()
{
Serial.begin(9600); // sets serial to 9600bps
}
void loop()
{
Serial.println(analogRead(A0)); // sends analog value
delay(1000); // pauses for 1 second
}

Verify button Upload button Serial Monitor

After entering your program, click on the Verify button for compilation. If there are errors, the
line numbers of the errors are shown in the bottom window. Correct the errors. After successful
verification, upload your program to the Arduino using the Upload button. A common cause for
failure in uploading is that your Arduino is not connected to a correct COM port of Arduino
Due.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 18
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 19
INTRODUCTION TO ATMEL SAM3X8E

The Atmel SMART SAM3X/A series is a member of a family of Flash microcontrollers based
on the high performance 32-bit ARM Cortex-M3 RISC processor. It operates at a maximum
speed of 84 MHz and features up to 512 Kbytes of Flash and up to 100 Kbytes of SRAM. The
peripheral set includes a High Speed USB Host and Device port with embedded transceiver, an
Ethernet MAC, 2 CANs, a High Speed MCI for SDIO/SD/MMC, an External Bus Interface with
NAND Flash Controller (NFC), 5 UARTs, 2 TWIs, 4 SPIs, as well as a PWM timer, three 3-
channel general-purpose 32-bit timers, a low-power RTC, a low-power RTT, 256-bit General
Purpose Backup Registers, a 12-bit ADC and a 12-bit DAC.

The SAM3X/A devices have three software-selectable low-power modes: Sleep, Wait and
Backup. In Sleep mode, the processor is stopped while all other functions can be kept running. In
Wait mode, all clocks and functions are stopped but some peripherals can be configured to wake
up the system based on predefined conditions. In Backup mode, only the RTC, RTT, and wake-
up logic are running.The SAM3X/A series is ready for capacitive touch thanks to the QTouch
library, offering an easy way to implement buttons, wheels and sliders.

The SAM3X/A architecture is specifically designed to sustain high-speed data transfers. It


includes a multi- layer bus matrix as well as multiple SRAM banks, PDC and DMA channels
that enable it to run tasks in parallel and maximize data throughput.The device operates from
1.62V to 3.6V and is available in 100 and 144-lead LQFP, 100-ball TFBGA and 144-ball
LFBGA packages.

The SAM3X/A devices are particularly well suited for networking applications: industrial and
home/building automation, gateways.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 20
Features:
Core
▪ ARM Cortex-M3 revision 2.0 running at up to 84 MHz

▪ Memory Protection Unit (MPU)

▪ Thumb -2 instruction set

▪ 24-bit SysTick Counter

▪ Nested Vector Interrupt Controller

Memories
▪ 256 to 512 Kbytes embedded Flash, 128-bit wide access, memory
accelerator, dual bank

▪ 32 to 100 Kbytes embedded SRAM with dual banks

▪ 16 Kbytes ROM with embedded bootloader routines (UART, USB) and


IAP routines

▪ Static Memory Controller (SMC): SRAM, NOR, NAND support. NFC


with 4 Kbyte RAM buffer and EC.

System
▪ Embedded voltage regulator for single supply operation

▪ Power-on-Reset (POR), Brown-out Detector (BOD) and Watchdog for


safe reset

▪ Quartz or ceramic resonator oscillators: 3 to 20 MHz main and optional


low power 32.768 kHz for RTC or device clock.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 21
▪ High precision 8/12 MHz factory trimmed internal RC oscillator with
4 MHz default frequency for fast device startup

▪ Slow Clock Internal RC oscillator as permanent clock for device clock in


low-power mode.One PLL for device clock and one dedicated PLL for
USB 2.0 High Speed Mini Host/Device.
Temperature Sensor
• Up to 17 peripheral DMA (PDC) channels and 6-channel central DMA
plus dedicated DMA for High-Speed USB Mini Host/Device and Ethernet
MAC
Low-power Modes
• Sleep, Wait and Backup modes, down to 2.5 µA in Backup mode with
RTC, RTT, and GPBR.

Peripherals
• USB 2.0 Device/Mini Host: 480 Mbps, 4 Kbyte FIFO, up to 10
bidirectional Endpoints, dedicated DMA.
• Up to 4 USARTs (ISO7816, IrDA®, Flow Control, SPI, Manchester and
LIN support) and one UART.
• 2 TWI (I2C compatible), up to 6 SPIs, 1 SSC (I2S), 1 HSMCI
(SDIO/SD/MMC) with up to 2 slots.
• 9-channel 32-bit Timer Counter (TC) for capture, compare and PWM
mode, Quadrature Decoder Logic and 2-bit Gray Up/Down Counter for
Stepper Motor
• Up to 8-channel 16-bit PWM (PWMC) with Complementary Output,
Fault Input, 12-bit Dead Time Generator Counter for Motor Control.
• 32-bit low-power Real-time Timer (RTT) and low-power Real-time Clock
(RTC) with calendar and alarm features.
• 256-bit General Purpose Backup Registers (GPBR).
• 16-channel 12-bit 1 msps ADC with differential input mode and
programmable gain stage.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 22
• 2-channel 12-bit 1 msps DAC

• Ethernet MAC 10/100 (EMAC) with dedicated DMA

• 2 CAN Controllers with 8 Mailboxes

• True Random Number Generator (TRNG)

• Register Write Protection

I/O
▪ Up to 103 I/O lines with external interrupt capability (edge or level
sensitivity), debouncing, glitch filtering and on-die Series Resistor
Termination.
▪ Up to six 32-bit Parallel Input/Outputs (PIO)

Packages

• 100-lead LQFP – 14 x 14 mm, pitch 0.5 mm

• 100-ball TFBGA – 9 x 9 mm, pitch 0.8 mm

• 144-lead LQFP – 20 x 20 mm, pitch 0.5 mm

• 144-ball LFBGA – 10 x 10 mm, pitch 0.8 mm

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 23
The SAM3X/A has different kinds of input/output (I/O) lines, such as general purpose I/Os
(GPIO) and system I/Os. GPIOs can have alternate functions thanks to multiplexing capabilities
of the PIO controllers. The same PIO line can be used whether in IO mode or by the multiplexed
peripheral. System I/Os include pins such as test pins, oscillators, erase or analog inputs.

General-purpose registers:R0-R12 are 32-bit general-purpose registers for data operations.

Stack Pointer:The Stack Pointer (SP) is register R13. In Thread mode, bit[1] of the CONTROL
register indicates the stack pointer to use:

0 = Main Stack Pointer (MSP). This is the reset value.


1 = Process Stack Pointer (PSP).
On reset, the processor loads the MSP with the value from address 0x00000000.

The Link Register (LR) is register R14. It stores the return information for subroutines, function
calls, and exceptions. On reset, the processor loads the LR value 0xFFFFFFFF.

Program Counter:The Program Counter (PC) is register R15. It contains the current program
address. Bit[0] is always 0 because instruction fetches must be halfword aligned. On reset, the
processor loads the PC with the value of the reset vector, which is at address 0x00000004.

Program Status Register:The Program Status Register (PSR) combines:

• Application Program Status Register (APSR)


• Interrupt Program Status Register (IPSR)
• Execution Program Status Register (EPSR).
These registers are mutually exclusive bit fields in the 32-bit PSR

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 24
DIGITAL IO

Description

The Digital IO features of the Arduino Due can be demonstrated with the GRIET LED and
switches shield. The Arduino Due has 54 digital IO pins – 0 to 53. The GRIET LED and
switches shield has 6 LEDs and 6 switches. The cathodes of the LEDs are grounded and the
anodes are connected to Arduino Due pins through resistors. The switches when pressed will
ground the connected Due pins. The Due pins connected to the switches should be made inputs
with pull-ups enabled. The required supply and ground for the shield are transferred from the
Arduino Due board

Pin-out:
LEDs and switches Arduino Due pins
LED1 8
LED2 9
LED3 10
LED4 11
LED5 12
LED6 13
S1 2
S2 3
S3 4
S4 5
S5 6
S6 7

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 25
Schematic

Note: The shield was developed for the Arduino UNO but is pin compatible for the Arduino
Due. The microcontroller pins shown in the schematic are for the ATmega328 and not for the
AT91SAM3X8E

Arduino Programs

1. The program will blink LED connected to pin 13 at a rate of 1 second

void setup()
{
pinMode(13,OUTPUT);
}

void loop()
{
digitalWrite(13,HIGH);
delay(1000);
digitalWrite(13,LOW);
}

2. The program will read the status of one switch and use it to control an LED – LED is on when
the switch is pressed and off when the switch is not pressed. LED1 and SW1 are used in the
program

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 26
int LED1 = 8;
int S1 = 2;

void setup( )
{
pinMode(LED1,OUTPUT);
pinMode(S1,INPUT_PULLUP);
}

void loop( )
{
int status;
status = digitalRead(S1);
if(status == LOW)
digitalWrite(LED1,HIGH);
else
digitalWrite(LED1,LOW);
}
Exercises:
1. Write an Arduino program to blink all six LEDs at a rate of 1 second
2. Write an Arduino program to control LED6 using switch SW6
3. Write an Arduino program to control the six LEDs using the six corresponding switches

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 27
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 28
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 29
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 30
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 31
ARM Programming: Parallel IO
Parallel IO:
The Parallel Input/Output Controller (PIO) manages up to 32 fully programmable
input/output lines. Each I/O line may be dedicated as a general-purpose I/O or be assigned to a
function of an embedded peripheral. This assures effective optimization of the pins of a product.
Each I/O line is associated with a bit number in all of the 32-bit registers of the 32-bit wide User
Interface.
Each I/O line of the PIO Controller features:

• An input change interrupt enabling level change detection on any I/O line.
• Additional Interrupt modes enabling rising edge, falling edge, low level or high level
detection on any I/O line.
• A glitch filter providing rejection of glitches lower than one-half of system clock cycle.
• A debouncing filter providing rejection of unwanted pulses from key or push button
operations.
• Multi-drive capability similar to an open drain I/O line.
• Control of the pull-up of the I/O line.
• Input visibility and output control.
• The PIO Controller also features a synchronous output providing up to 32 bits of data
output in a single write operation.
PIO Controllers: PIOA, PIOB, PIOC and PIOD

Pin Multiplexing:

Each pin is configurable, according to product definition as either a general-purpose I/O line
only, or as an I/O line multiplexed with one or two peripheral I/Os. As the multiplexing is
hardware defined and thus product-dependent, the hardware designer and programmer must
carefully determine the configuration of the PIO controllers required by their application. When
an I/O line is general-purpose only, i.e. not multiplexed with any peripheral I/O, programming of

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 32
the PIO Controller regarding the assignment to a peripheral has no effect and only the PIO
Controller can control how the pin is driven by the product.

Power Management:

The Power Management Controller controls the PIO Controller clock in order to save power.
Writing any of the registers of the user interface does not require the PIO Controller clock to be
enabled. This means that the configuration of the I/O lines does not require the PIO Controller
clock to be enabled. However, when the clock is disabled, not all of the features of the PIO
Controller are available, including glitch filtering. Note that the Input Change Interrupt, Interrupt
Modes on a programmable event and the read of the pin level require the clock to be validated.
After a hardware reset, the PIO clock is disabled by default. The user must configure the Power
Management Controller before any access to the input line information.

Pull-up Resistor Control:

Each I/O line is designed with an embedded pull-up resistor. The pull-up resistor can be enabled
or disabled by writing respectively PIO_PUER (Pull-up Enable Register) and PIO_PUDR
(Pullup Disable Resistor). Writing in these registers results in setting or clearing the
corresponding bit in PIO_PUSR (Pull-up Status Register). Reading a 1 in PIO_PUSR means the
pull-up is disabled and reading a 0 means the pull-up is enabled. Control of the pull-up resistor is
possible regardless of the configuration of the I/O line. After reset, all of the pull-ups are
enabled, i.e. PIO_PUSR resets at the value 0x0.

I/O Line or Peripheral Function Selection:

When a pin is multiplexed with one or two peripheral functions, the selection is
controlled with the registers PIO_PER (PIO Enable Register) and PIO_PDR (PIO Disable
Register). The register PIO_PSR (PIO Status Register) is the result of the set and clear registers
and indicates whether the pin is controlled by the corresponding peripheral or by the PIO
Controller. A value of 0 indicates that the pin is controlled by the corresponding on-chip

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 33
peripheral selected in the PIO_ABSR (AB Select Register). A value of 1 indicates the pin is
controlled by the PIO controller.

Output Control

When the I/0 line is assigned to a peripheral function, i.e. the corresponding bit in PIO_PSR is at
0, the drive of the I/O line is controlled by the peripheral. Peripheral A or B depending on the
value in PIO_ABSR (AB Select Register) determines whether the pin is driven or not. When the
I/O line is controlled by the PIO controller, the pin can be configured to be driven. This is done
by writing PIO_OER (Output Enable Register) and PIO_ODR (Output Disable Register). The
results of these write operations are detected in PIO_OSR (Output Status Register). When a bit in
this register is at 0, the corresponding I/O line is used as an input only. When the bit is at 1, the
corresponding I/O line is driven by the PIO controller.

The level driven on an I/O line can be determined by writing in PIO_SODR (Set Output Data
Register) and PIO_CODR (Clear Output Data Register). These write operations respectively set
and clear PIO_ODSR (Output Data Status Register), which represents the data driven on the I/O
lines. Writing in PIO_OER and PIO_ODR manages PIO_OSR whether the pin is configured to
be controlled by the PIO controller or assigned to a peripheral function. This enables
configuration of the I/O line prior to setting it to be managed by the PIO Controller. Similarly,
writing in PIO_SODR and PIO_CODR effects PIO_ODSR. This is important as it defines the
first level driven on the I/O line.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 34
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 35
ARM code
Example 1:

The program will blink LED connected to pin 13. Pin 13 is B27 pin of SAM3X
#define LED0_MASK (1<<27)
void setup() {
// put your setup code here, to run once:
PIOB->PIO_PER = LED0_MASK;
PIOB ->PIO_OER = LED0_MASK;
PIOB ->PIO_PUDR = LED0_MASK;
}
void loop() {
// put your main code here, to run repeatedly:
PIOB ->PIO_SODR = LED0_MASK;
delay(1000);
PIOB ->PIO_CODR = LED0_MASK;
delay(1000);}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 36
Example 2:

In this example, LED connected to Arduino Due pin 8 (C22 of SAMX) is controlled by switch
connected to Due pin 2 (B25 of SAMX)

#define LED0_PIO PIOC


unsigned long LED0_MASK = (1<<22);
#define SW0_PIO PIOB
unsigned long SW0_MASK = (1<<25);
void setup() {
// put your setup code here, to run once:
LED0_PIO->PIO_PER = LED0_MASK;
LED0_PIO->PIO_OER = LED0_MASK;
LED0_PIO->PIO_PUDR = LED0_MASK;
pmc_enable_periph_clk(ID_PIOB);
SW0_PIO->PIO_PER = SW0_MASK;
SW0_PIO->PIO_ODR = SW0_MASK;
SW0_PIO->PIO_PUER = SW0_MASK;
}
void loop() {
// put your main code here, to run repeatedly:
if((SW0_PIO->PIO_PDSR & SW0_MASK) == 0)
LED0_PIO->PIO_SODR = LED0_MASK;
else
LED0_PIO->PIO_CODR = LED0_MASK;
}

Exercises:

1.Write an ARM program to configure and control General Purpose Input/Output (GPIO)port
pins.
2.Write an ARM program to control the six LEDs using the six corresponding switches.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 37
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 38
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 39
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 40
Serial communication

Description:

The Arduino Due board is capable of serial communication used for communication between
the Arduino board and a computer or other devices. The SAM3X provides one hardware UART
and three hardware USARTs for TTL (3.3V) serial communication. The Programming port is
connected to an ATmega16U2, which provides a virtual COM port to software on a connected
computer.The 16U2 is also connected to the SAM3X hardware UART. Serial on pins RX0
andTX0 provides Serial-to-USB communication for programming the board through the
ATmega16U2 microcontroller. The Arduino software includes a serial monitor which allows
simple textual data to be sent to and from the board.

Due has three additional 3.3V TTL serial ports:


Serial1 on pins 19 (RX) and 18 (TX)
Serial2 on pins 17 (RX) and 16 (TX)
Serial3 on pins 15 (RX) and 14 (TX).
To use these pins to communicate with your personal computer, you will need an additional
USB-to-serial adaptor, as they are not connected to the Due’s USB-to-serial adaptor. To use
them to communicate with an external TTL serial device, connect the TX pin to your device's
RX pin, the RX to your device's TX pin, and the ground of your Due to your device's ground.
(Don't connect these pins directly to an RS232 serial port; they operate at +/- 12V and can
damage your Arduino board.)
Functions
begin()
Description
Sets the data rate in bits per second (baud) for serial data transmission. For
communicating with the computer, use one of these rates: 300, 1200, 2400, 4800, 9600, 14400,
19200, 28800, 38400, 57600, or 115200.
Syntax
Serial.begin(speed)

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 41
println()
Description
Prints data to the serial port as human-readable ASCII text followed by a carriage return
character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n'). This command takes the
same forms as Serial.print().

Syntax
Serial.println(val)
Serial.println(val, format)

Parameters
val: the value to print - any data type
format: specifies the number base (for integral data types) or number of decimal places (for
floating point types)
Returns
byte
println() will return the number of bytes written, though reading that number is optional
Example:
void setup() {
// open the serial port at 9600 bps:
Serial.begin(9600);
}

void loop() {
println(“Hello World”);
delay(1000);
}

Exercises
1.Write a Program for UART-Echo test.

2.Write a program to control the LED s based on commands from Serial monitor.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 42
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 43
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 44
ARM Serial Programming: UART

UART:
The Universal Asynchronous Receiver Transmitter features a two-pin UART that can be used for
communication
Two-pin UART Implemented Features are
• USART Compatible
o Independent Receiver and Transmitter with a Common Programmable Baud Rate
• Generator
o Even, Odd, Mark or Space Parity Generation
o Parity, Framing and Overrun Error Detection
o Automatic Echo, Local Loopback and Remote Loopback Channel Modes
o Interrupt Generation
o Support for Two PDC Channels with Connection to Receiver and Transmitter
The UART pins are multiplexed with PIO lines. The programmer must first configure the
corresponding PIO Controller to enable I/O line operations of the UART.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 45
Baud Rate

The baud rate generator provides the bit period clock named baud rate clock to both the
receiverand the transmitter. The baud rate clock is the master clock divided by 16 times the value
(CD) written in UART_BRGR (Baud Rate Generator Register). If UART_BRGR is set to 0, the
baud rate clock is disabled and the UART remains inactive. The maximum allowable baud rate is
Master Clock divided by 16. The minimum allowable baud rate is Master Clock divided by (16 x
65536). Baud Rate = MCK/16 × CD.

Receiver
After device reset, the UART receiver is disabled and must be enabled before being used.
The receiver can be enabled by writing the control register UART_CR with the bit RXEN at 1.
At this command, the receiver starts looking for a start bit. When a complete character is
received, it is transferred to the UART_RHR and the RXRDY status bit in UART_SR (Status
Register) is set. The bit RXRDY is automatically cleared when the receive holding register
UART_RHR is read.

Transmitter
After device reset, the UART transmitter is disabled and it must be enabled before being
used. The transmitter is enabled by writing the control register UART_CR with the bit TXEN at
1. From this command, the transmitter waits for a character to be written in the Transmit Holding
Register (UART_THR) before actually starting the transmission. When the transmitter is
enabled, the bit TXRDY (Transmitter Ready) is set in the status register UART_SR. The
transmission starts when the programmer writes in the Transmit Holding Register
(UART_THR), and after the written character is transferred from UART_THR to the Shift
Register. The TXRDY bit remains high until a second character is written in UART_THR. As
soon as the first character is completed, the last character written in UART_THR is transferred

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 46
into the shift register and TXRDY rises again, showing that the holding register is empty. When
both the Shift Register and UART_THR are empty, i.e., all the characters written in UART_THR
have been processed, the TXEMPTY bit rises after the last stop bit has been completed.

UART Control Register

• RSTRX: Reset Receiver 0 = No effect.

1 = The receiver logic is reset and disabled. If a character is being received, the reception is
aborted.
• RSTTX: Reset Transmitter
0 = No effect.
1 = The transmitter logic is reset and disabled. If a character is being transmitted, the
transmission is aborted.
• RXEN: Receiver Enable
0 = No effect.
1 = The receiver is enabled if RXDIS is 0.
• RXDIS: Receiver Disable
0 = No effect.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 47
1 = The receiver is disabled. If a character is being processed and RSTRX is not set, the
character is completed before the receiver is stopped.
• TXEN: Transmitter Enable
0 = No effect.
1 = The transmitter is enabled if TXDIS is 0.
• TXDIS: Transmitter Disable
0 = No effect.
1 = The transmitter is disabled. If a character is being processed and a character has been
written in the UART_THR and RSTTX is not set, both characters are completed before the
transmitter is stopped.
• RSTSTA: Reset Status Bits
0 = No effect.
1 = Resets the status bits PARE, FRAME and OVRE in the UART_SR.

UART Mode Register

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 48
UART Interrupt Enable Register

RXRDY: Enable RXRDY Interrupt

TXRDY: Enable TXRDY Interrupt

ENDRX: Enable End of Receive Transfer Interrupt

ENDTX: Enable End of Transmit Interrupt

OVRE: Enable Overrun Error Interrupt

FRAME: Enable Framing Error Interrupt

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 49
PARE: Enable Parity Error Interrupt

TXEMPTY: Enable TXEMPTY Interrupt

TXBUFE: Enable Buffer Empty Interrupt

RXBUFF: Enable Buffer Full Interrupt

0 = No effect.

1 = Enables the corresponding interrupt.

UART Status Register

RXRDY: Receiver Ready

0 = No character has been received since the last read of the UART_RHR or
the receiver is disabled.

1 = At least one complete character has been received, transferred to


UART_RHR and not yet read.

TXRDY: Transmitter Ready

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 50
0 = A character has been written to UART_THR and not yet transferred to the Shift Register, or
the transmitter is disabled.

1 = There is no character written to UART_THR not yet transferred to the Shift Register.

ENDRX: End of Receiver Transfer

0 = The End of Transfer signal from the receiver Peripheral Data


Controller channel is inactive.

1 = The End of Transfer signal from the receiver Peripheral Data


Controller channel is active.

ENDTX: End of Transmitter Transfer

0 = The End of Transfer signal from the transmitter Peripheral Data


Controller channel is inactive.

1 = The End of Transfer signal from the transmitter Peripheral Data


Controller channel is active.

OVRE: Overrun Error

0 = No overrun error has occurred since the last RSTSTA.

1 = At least one overrun error has occurred since the last RSTSTA.

FRAME: Framing Error

0 = No framing error has occurred since the last RSTSTA.

1 = At least one framing error has occurred since the last RSTSTA.

PARE: Parity Error

0 = No parity error has occurred since the last RSTSTA.

1 = At least one parity error has occurred since the last RSTSTA.

TXEMPTY: Transmitter Empty

0 = There are characters in UART_THR, or characters being processed by the transmitter, or


the transmitter is disabled.

1 = There are no characters in UART_THR and there are no characters being processed by the
transmitter.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 51
TXBUFE: Transmission Buffer Empty

0 = The buffer empty signal from the transmitter


PDC channel is inactive.

1 = The buffer empty signal from the transmitter


PDC channel is active.

RXBUFF: Receive Buffer Full

0 = The buffer full signal from the receiver


PDC channel is inactive.

1 = The buffer full signal from the receiver


PDC channel is active.

UART Receiver Holding Register

RXCHR: Received Character

Last received character if RXRDY is set.


UART Transmit Holding Register

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 52
TXCHR: Character to be Transmitted
Next character to be transmitted after the current character if TXRDY is not set.

UART Baud Rate Generator Register

CD: Clock Divisor

0 = Baud Rate Clock is disabled

1 to 65,535 = MCK / (CD x 16)

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 53
ARM code
In this example, the baud rate is set to 9600, receiver and transmitter are enabled and any
character received is transmitted back.
void setup() {
// put your setup code here, to run once:
// Configure PMC
pmc_enable_periph_clk(ID_UART);
// Disable PDC channel
UART->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ;
// Reset and disable receiver and transmitter
UART->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS |
UART_CR_TXDIS;
// Configure mode
UART->UART_MR = UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL ;
// Configure baudrate (asynchronous, no oversampling)
UART->UART_BRGR = (SystemCoreClock / 9600) >> 4 ;
// Enable receiver and transmitter
UART->UART_CR = UART_CR_RXEN | UART_CR_TXEN ;
}

void loop() {
// put your main code here, to run repeatedly:
uint32_t mymask = 1;
uint32_t mydata;
uint32_t status1 = UART->UART_SR;
// Did we receive data ?
while((UART->UART_SR & UART_SR_RXRDY) != UART_SR_RXRDY);
mydata = UART->UART_RHR;
while ((UART->UART_SR & UART_SR_TXRDY) != UART_SR_TXRDY) ;
// Send character
UART->UART_THR = mydata;
}

Exercises:

1.Write a ARM program to Receive a character from the Serial Monitor. If the character is ‘1’,
switch on LED connected to pin 13, if it is ‘0’ switch off the LED. Use the ARM registers in
your code .

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 54
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 55
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 56
ARDUINO TIMERS and INTERRUPT FUNCTIONS
millis()

Description
Returns the number of milliseconds since the Arduino board began running the current program.
This number will overflow (go back to zero), after approximately 50 days.

Parameters
None

Returns
Number of milliseconds since the program started (unsigned long)

Note:
Please note that the return value for millis() is an unsigned long, logic errors may occur if a
programmer tries to do arithmetic with smaller data types such as int's. Even signed long may
encounter errors as its maximum value is half that of its unsigned counterpart.

Example

unsigned long time;

void setup(){
Serial.begin(9600);
}
void loop(){
Serial.print("Time: ");
time = millis();
//prints time since program started
Serial.println(time);
// wait a second so as not to send massive amounts of data
delay(1000);
}

micros()

Description
Returns the number of microseconds since the Arduino board began running the current
program. This number will overflow (go back to zero), after approximately 70 minutes. On
16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 57
microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards
(e.g. the LilyPad), this function has a resolution of eight microseconds.

Note: there are 1,000 microseconds in a millisecond and 1,000,000 microseconds in a second.

Parameters
None

Returns
Number of microseconds since the program started (unsigned long)

Example

unsigned long time;

void setup(){

Serial.begin(9600);

void loop(){

Serial.print("Time: ");

time = micros();

//prints time since program started

Serial.println(time);

// wait a second so as not to send massive amounts of data

delay(1000);

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 58
delay()

Description
Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are
1000 milliseconds in a second.)

Syntax
delay(ms)

Parameters
ms: the number of milliseconds to pause (unsigned long)

Example
int ledPin = 13; // LED connected to digital pin 13

void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}

void loop()
{
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}

delayMicroseconds()

Description
Pauses the program for the amount of time (in microseconds) specified as parameter. There are a
thousand microseconds in a millisecond, and a million microseconds in a second.

Currently, the largest value that will produce an accurate delay is 16383. This could change in
future Arduino releases. For delays longer than a few thousand microseconds, you should use
delay() instead.

Syntax
delayMicroseconds(us)

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 59
Parameters
us: the number of microseconds to pause (unsigned int)

Example
int outPin = 8; // digital pin 8

void setup()
{
pinMode(outPin, OUTPUT); // sets the digital pin as output
}

void loop()
{
digitalWrite(outPin, HIGH); // sets the pin on
delayMicroseconds(50); // pauses for 50 microseconds
digitalWrite(outPin, LOW); // sets the pin off
delayMicroseconds(50); // pauses for 50 microseconds
}

configures pin number 8 to work as an output pin. It sends a train of pulses of


approximately 100 microseconds period. The approximation is due to execution of the
other instructions in the code.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 60
INTERRUPTS

Description :Re-enables interrupts (after they've been disabled by noInterrupts()). Interrupts


allow certain important tasks to happen in the background and are enabled by default. Some
functions will not work while interrupts are disabled, and incoming communication may be
ignored. Interrupts can slightly disrupt the timing of code, however, and may be disabled for
particularly critical sections of code.

attachInterrupt()

Description:Digital Pins With Interrupts -The first parameter to attachInterrupt is an interrupt


number. Normally you should use digitalPinToInterrupt(pin) to translate the actual digital pin to
the specific interrupt number. For example, if you connect to pin 3, use digitalPinToInterrupt(3)
as the first parameter to attachInterrupt.

Board Digital Pins Usable For Interrupts

Uno, Nano, Mini, other 328-based 2, 3

Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21

Micro, Leonardo, other 32u4-based 0, 1, 2, 3, 7

Zero all digital pins, except 4

Due all digital pins

Note :Inside the attached function, delay() won't work and the value returned by millis() will not
increment. Serial data received while in the function may be lost. You should declare as volatile
any variables that you modify within the attached function. See the section on ISRs below for
more information.

Using Interrupts
Interrupts are useful for making things happen automatically in microcontroller programs, and
can help solve timing problems. Good tasks for using an interrupt may include reading a rotary
encoder, or monitoring user input.
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 61
About Interrupt Service Routines
ISRs are special kinds of functions that have some unique limitations most other functions do not
have. An ISR cannot have any parameters, and they shouldn't return anything.

Generally, an ISR should be as short and fast as possible. If your sketch uses multiple ISRs, only
one can run at a time, other interrupts will be executed after the current one finishes in an order
that depends on the priority they have. millis() relies on interrupts to count, so it will never
increment inside an ISR. Since delay() requires interrupts to work, it will not work if called
inside an ISR. micros() works initially, but will start behaving erratically after 1-2 ms.
delayMicroseconds() does not use any counter, so it will work as normal.

Typically global variables are used to pass data between an ISR and the main program. To make
sure variables shared between an ISR and the main program are updated correctly, declare them
as volatile.

Syntax

attachInterrupt(digitalPinToInterrupt(pin), (recommended)
ISR, mode);

attachInterrupt(interrupt, ISR, mode); (not recommended)

attachInterrupt(pin, ISR, mode) ; (not recommended


Arduino Due, Zero only)

Parameters
interrupt: the number of the interrupt (int)

pin: the pin number (Arduin


o Due,
Zero
only)

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 62
ISR: the ISR to call when the interrupt occurs; this function must take
no parameters and return nothing. This function is sometimes
referred to as an interrupt service routine.

mode:
defines when the interrupt should be triggered. Four contstants
are predefined as valid values:

• LOW to trigger the interrupt whenever the pin is low,


• CHANGE to trigger the interrupt whenever the pin changes value
• RISING to trigger when the pin goes from low to high,
• FALLING for when the pin goes from high to low.

The Due board allows also:


• HIGH to trigger the interrupt whenever the pin is high. (Arduino
Due,
Zero
only)
Example
int pin = 13;
volatile int state = LOW;

void setup() {
pinMode(pin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE
);
}

void loop() {
digitalWrite(pin, state);
}

void blink() {
state = !state;
}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 63

Interrupt numbers

Normally you should use digitalPinToInterrupt(pin), rather than place interrupt


an number directly into your sketch. The specific pins with interrupts, and their
mapping to interrupt number varies on each type of board. Direct use of
interrupt numbers may seem simple, but it can cause compatibility trouble
when your sketch is run on a different board.However, older sketches often
have direct interrupt numbers. Often number 0 (for digital pin 2) or number 1
(for digital pin 3) were used. The table below shows the available interrupt
pins on various boards.

Board int.0 int.1 int.2 int.3 int.4 int.5

Uno, Ethernet 2 3

Mega2560 2 3 21 20 19 18

32u4 based (e.g Leonardo,


3 2 0 1 7
Micro)

The Arduino Due board has powerful interrupt capabilities that allows you to
attach an interrupt function on all available pins. You can directly specify the
pin number in attachInterrupt().

The Arduino Zero board allows you to attach an interrupt function on all
available pins except for pin 4. You can directly specify the pin number in
attachInterrupt().

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 64
detachInterrupt()

Description

Turns off the given interrupt.

Syntax

detachInterrupt(interrupt)

detachInterrupt(digitalPinToInterrupt(pin));

detachInterrupt(pin) (Arduino Due, Zero only)

Parameters

• interrupt: the number of the interrupt to disable (see attachInterrupt() for more details).
• pin: the pin number of the interrupt to disable (Arduino Due only)

Exercise

1.Program demonstrates setting up interrupt handlers. Press button to generate an interrupt


and trace the program flow with debug terminal.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 65
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 66
ANALOG INPUTS

Description
Temperature and LDR sensors are using in this experiment The temperature sensor is connected
to pin A0 and the ambient light sensor is connected to pin A1 of Due. To use the internal ADC,
the function AnalogRead() is used.
analogRead()
Description
The Due has 12 analog inputs, each of which can provide 12 bits of resolution (i.e. 4096 different
values). By default, the resolution of the readings is set at 10 bits, for compatibility with other
Arduino boards. It is possible to change the resolution of the ADC with analogReadResolution().
The Due’s analog inputs pins measure from ground to a maximum value of 3.3V. Applying more
then 3.3V on the Due’s pins will damage the SAM3X chip. The analogReference() function is
ignored on the Due.
analogRead(pin)
Parameters
pin: the number of the analog input pin to read from (A0 to A11 on Due)
Returns
int (0 to 1023)
analogReadResolution()
Des cri p ti on
analogReadResolution() is an extension of the Analog API for the Arduino Due.
Sets the size (in bits) of the value returned by analogRead(). It defaults to 10 bits (returns values
between 0-1023) for backward compatibility with AVR based boards.
The Due has 12-bit ADC capabilities that can be accessed by changing the resolution to 12.
This will return values from analogRead() between 0 and 4095.
S yn tax
analogReadResolution(bits)

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 67
Para met ers
bits: determines the resolution (in bits) of the value returned by analogRead() function. You can
set this 1 and 32. You can set resolutions higher than 12 but values returned by analogRead() will
suffer approximation. See the note below for details.
Retu rn s
None.
Note
If you set the analogReadResolution() value to a value higher than your board's capabilities, the
Arduino will only report back at its highest resolution padding the extra bits with zeros.
For example: using the Due with analogReadResolution(16) will give you an approximated 16-
bit number with the first 12 bits containing the real ADC reading and the last 4 bits padded with
zeros.
If you set the analogReadResolution() value to a value lower than your board's capabilities, the
extra least significant bits read from the ADC will be discarded.
Using a 16 bit resolution (or any resolution higher than actual hardware capabilities) allows you
to write sketches that automatically handle devices with a higher resolution ADC when these
become available on future boards without changing a line of code.

Schematic

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 68
Arduino program

1. This program reads the analog input at A1 and displays it in the Serial Monitor

int val = 0; // variable to store the value read


void setup()
{
Serial.begin(9600); // setup serial
}

void loop()
{
val = analogRead(A1); // read the input pin
Serial.println(val); // debug value
}

Exercises

1.Write a Program to get analog input from Temperature sensor and display the temperature
value on the Serial monitor.

2.Write a program to read the LDR sensor, convert the value into voltage and display it on
the serial monitor.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 69
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 70
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 71
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 72
Parallel interface: 2x16 LCD
Description
A 2x16 caharacter LCD is an example of a parallel interface. It has an 8-bit data bus to which
commands and data for display can be transferred in parallel.The 2x16 LCD uses the 4-bit
interface. The RD/WR pin of the LCD is grounded so that write is permanently enabled. There is
a potentiometer for adjusting the contrast. Adjust the pot till you see a strip of dark blocks in the
first line of the LCD. The pin-out of the 2x16 LCD used in the LCD shield is :

LCD Pin Description

Pin Name Description


1 VSS GND
2 VCC +5V
3 VEE Contrast Adjust
4 RS (Register Select) 0=Instruction 1= Data
5 R/W(Read/Write) 0=Write 1= Read
6 EN Enable Signal
7 D0 Data Bus Line 0 (LSB)
8 D1 Data Bus Line 1
9 D2 Data Bus Line 2

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 73
10 D3 Data Bus Line 3
11 D4 Data Bus Line 4
12 D5 Data Bus Line 5
13 D6 Data Bus Line 6
14 D7 Data Bus Line 7(MSB)

Pin-out &Schematic

LCD Arduino Due pins


LCD Enable 9
LCD Register Select(RS) 8
DB4 4
DB5 5
DB6 6
DB7 7

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 74
Arduino program

The program is to write “Hello World” in the first line of the LCD. We use the LiquidCrystal.h
library in the program.
#include <LiquidCrystal.h>
/* RS 12
E 11
D4 4
D6 5
D7 6
D8 7 */
LiquidCrystal lcd(8,9,4,5,6,7);
void setup()
{
lcd.begin(16,2);
lcd.print(" hello, world");
}
void loop()
{
}
Note: The shield was developed for the Arduino UNO but is pin compatible for the Arduino
Due. The microcontroller pins shown in the schematic are for the ATmega328 and not for the
AT91SAM3X8E.

LCD library functions


LiquidCrystal()
Description
Creates a variable of type LiquidCrystal. The display can be controlled using 4 or 8 data
lines. If the former, omit the pin numbers for d0 to d3 and leave those lines unconnected. 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, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)
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

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 75
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).
begin()
Description
Specifies the dimensions (width and height) of the display.
Syntax
lcd.begin(cols, rows)
Parameters
lcd: a variable of type LiquidCrystal
cols: the number of columns that the display has
rows: the number of rows that the display has
setCursor()
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)
Parameters
lcd: a variable of type LiquidCrystal
col: the column at which to position the cursor (with 0 being the first column)
row: the row at which to position the cursor (with 0 being the first row)

Exercises:
1. Write a program to interface the ARM with LCD and display the message on LCD whenever
character sends from system(serial monitor).
2.Write an application that creates a task displaying two different messages on LCD in two
lines.(Temperature sensor readings(ADC value, voltage and temperature) displayed on 1st line
LDR readings on 2nd line of LCD).

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 76
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 77
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 78
RFID TECHNOLOGY

RFID stands for Radio Frequency Identification. it uses radio waves to automatically identify
people or objects. RFID is an automated data-capture technology that can be used to
electronically identify, track, and store information contained on a tag. A radio frequency reader
scans the tag for data and sends the information to a database, which stores the data contained on
the tag.
Identification processes that rely on AIDC technologies are significantly more reliable and less
expensive than those that are not automated. The most common AIDC technology is bar code
technology, which uses optical scanners to read labels. Most people have direct experience with
bar codes because they have seen cashiers scan items at supermarkets and retail stores. Bar codes
are an enormous improvement over ordinary text labels because personnel are no longer required
to read numbers or letters on each label or manually enter data into an IT system; they just have
to scan the label. The innovation of bar codes greatly improved the speed and accuracy of the
identification process and facilitated better management of inventory and pricing when coupled
with information systems.

RFID represents a technological advancement in AIDC because it offers advantages that are not
available in other AIDC systems such as bar codes. RFID offers these advantages because it
relies on radio frequencies to transmit information rather than light, which is required for optical
AIDC technologies. The use of radio frequencies means that RFID communication can occur:
• Without optical line of sight, because radio waves can penetrate many materials,
• At greater speeds, because many tags can be read quickly, whereas optical technology
often requires time to manually reposition objects to make their bar codes visible, and
• Over greater distances, because many radio technologies can transmit and receive signals
more effectively than optical technology under most operating conditions
The ability of RFID technology to communicate without optical line of sight and over
greater distances than other AIDC technology further reduces the need for human involvement in
the identification process. For example, several retail firms have pilot RFID programs to
determine the contents of a shopping cart without removing each item and placing it near a

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 79
scanner, as is typical at most stores today. In this case, the ability to scan a cart without removing
its contents could speed up the checkout process, thereby decreasing transaction costs for the
retailers. This application of RFID also has the potential to significantly decrease checkout time
for consumers.
RFID products often support other features that bar codes and other AIDC technologies do not
have, such as rewritable memory, security features, and environmental sensors that enable the
RFID technology to record a history of events. The types of events that can be recorded include
temperature changes, sudden shocks, or high humidity. Today, people typically perceive the
label identifying a particular object of interest as static, but RFID technology can make this label
dynamic or even “smart” by enabling the label to acquire data about the object even when people
are not present to handle it.
COMPONENTS OF RFID SYSTEM
Radio frequency identification (RFID) is a technology that allows automatic identification and
data capture by using radio frequencies. The salient features of this technology are that they
permit the attachment of a unique identifier and other information – using a micro-chip – to any
object, animal or even a person, and to read this information through a wireless device. RFIDs
are not just "electronic tags" or "electronic barcodes". When linked to databases and
communications networks, such as the Internet, this technology provides a very powerful way of
delivering new services and applications, in potentially any environmentThe main technology
components of an RFID system are a tag, reader, and database. A radio frequency reader scans
the tag for data and sends the information to a database, which stores the data contained on the
tag.

Block diagram of RFID system


GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 80
RFID FRQUENCIES:

RFID tags and readers must be tuned into the same frequency to enable communications. RFID
systems can use a variety of frequencies to communicate, but because radio waves work and act
differently at different frequencies, a frequency for a specific RFID system is often dependant on
its application. High frequency RFID systems (850 MHz to 950 MHz and 2.4 GHz to 2.5 GHz)
offer transmission ranges of more than 90 feet, although wavelengths in the 2.4 GHz range are
absorbed by water, which includes the human body, and therefore has limitations.

RFID tag: An RFID tag, or transponder, consists of a chip and an antenna .A chip can store a
unique serial number or other information based on the tag’s type of memory, which can be read-
only, read-write, or write-once read-many. The antenna, which is attached to the microchip,
transmits information from the chip to the reader. Typically, a larger antenna indicates a longer
read range. The tag is attached to or embedded in and object to be identified, such as a product,
case, or pallet, and can be scanned by mobile or stationary readers using radio wave

RFID tag

RFID tag

Tags are classified into different types based on battery and memory. They are
• Passive tags
• Active tags
• Semi passive tags

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 81
RFID READER:
Radio Frequency Identification (RFID) Card Readers provide a low-cost solution to read passive
RFID transponder tags up to 7 cm away. This RFID Card Reader can be used in a wide variety of
hobbyist and commercial applications, including access control, automatic identification,
robotics navigation, inventory tracking, payment systems, and car immobilization. The RFID
card reader read the RFID tag in range and outputs unique identification code of the tag at baud
rate of 9600. The data from RFID reader can be interfaced to be read by microcontroller or PC.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 82
RFID reader
Features:
• Low-cost method for reading passive RFID transponder tags
• 9600 bps serial interface at 5V TTL level for direct interface to microcontrollers
• Buzzer & LED indicate valid RFID Tag detection
• Range up to 7 cm for 125 Khz RFID Cards or Keychains

Specification:

Communication:

When the RFID Card Reader is active and a valid RFID transponder tag is placed within range of
the activated reader, the unique ID will be transmitted as a 12-byte printable ASCII string
serially to the host in the following format:

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 83
The start byte and stop byte are used to easily identify that a correct string has been received
from the reader (they correspond to a line feed and carriage return characters, respectively). The
middle ten bytes are the actual tag's unique ID.For example, for a tag with a valid ID of
0F0184F07A, the following ASCII data would be sent 0F0184F07A Same data in HEX bytes
can be interpreted as:0x0A, 0x30, 0x46, 0x30, 0x31, 0x38, 0x34, 0x46, 0x30, 0x37, 0x41,
0x0DAll communication is 8 data bits, no parity, 1 stop bit, and least significant bit first (8N1).
The baud rate is configured for 9600 bps, a standard communications speed supported by most
any microprocessor or PC, and cannot be changed. The RFID Card Reader initiates all
communication. This allows easy access to the serial data stream from any programming
language that can open a COM port.
Using RFID Reader
When powered on the RFID reader will activate a RF field waiting for a tag to come into its
range. Once tag is detected, its unique ID number is read and data is sent via serial interface. The
valid tag detecting is indicated by LED blink and Buzzer beep. The face of the RFID tag should
be held parallel to the front of the antenna (where the majority of RF energy is focused). If the
tag is held sideways (perpendicular to the antenna) you may have difficulty getting the tag to be
read. Only one transponder tag should be held up to the antenna at any time. The use of multiple
tags at one time will cause tag collisions and confuse the reader. The tags available with us have
a read distance of approximately 7 cm. Actual distance may vary slightly depending on the size
of the transponder tag and environmental conditions of the application.

RFID reader interfacing with Microcontroller:


Connect data output pin of RFID reader to RXD pin of any microcontroller and configure your
MCU to receive data at 9600 baud rate. You also have to keep common ground signal between
RFID reader and microcontroller.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 84
Program to interface RFID reader with ARM and display the RFID TAG number
on the serial monitor.
char d[10];

void setup()

Serial.begin(9600);

Serial1.begin(9600);

// put your setup code here, to run once:

void loop()

while(Serial1.available()==0);
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 85
if(Serial1.read()==0x0a)

for(int i=0;i<10;i++)

while(Serial1.available()==0);

d[i]=Serial1.read();

Serial.write(d[i]);

}delay(1000);

// put your main code here, to run repeatedly:

Exercise
Write a Program to implement RFID based access control system

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 86
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 87
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 88
BLUETOOTH

Introduction
BlueTooth module has BlueTooth on one side and serial interface on the other. It has five pins :
VCC, GND, TX, RX and RESET. The TX pin of BlueLink is connected to RX of Arduino and
RX connected to TX of Arduino. Data received on BlueTooth is transferred to Arduino serial
port and data sent from the Arduino serial port is sent over BlueTooth. These data transfers
between the Arduino and BlueLink take place at a baud rate of 9600.

Pin-out
BlueLink pins Arduino Uno pins ATmega328 pin

TX 0(RX) PD0

RX 1(TX) PD1

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 89
Program to transfer a message “Microcontrollers lab” to Android based mobile using ARM,
Bluetooth module and Blue term app

void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println(““Microcontrollers lab”);
delay(1000);}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 90
Execise:
Write a Program to Develop Bluetooth based monitoring and appliance control System.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 91
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 92
ZIGBEE
Introduction
ZigBee module allows the ARM board to communicate wirelessly using the XBee
module. The XBee Series 2 module from Digi has a range of 100 feet indoors and works at
2.4GHz. For establishing wireless networking using the Series 2 modules, there should be a
ZigBee co-ordinator module and one or more ZigBee router/end-point modules.

The ZigBee dongle is made the co-ordinator by loading the co-ordinator firmware in its
XBee. Router firmware is loaded in the XBee of the ZigBee shield. X-CTU software from Digi
is used for loading the firmware as well as for setting module parameters. The Pan ID of both
modules should be the same. Note down the SH and SL parameters of the XBee co-ordinator
module and set the DH and DL of the router module equal to SH and SL respectively.
Pin-out
XBee pins Arduino Uno pins ATmega328 pin

Dout 0(RX) PD0

Din 1(TX) PD1

Schematic

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 93
802.15.4 is a standard for wireless communication issued by IEEE(Institute for Electrical and
Electronics Engineers). The standard specifies that communication can occur in the 868-868.8
MHz, the 902-928 MHz and the 2.400-2.4835 GHz ISM (Industrial, Scientific and Medical
bands. While any of these bands can be technically used by 802.15.4 devices, the 2.4 GHz band
is more popular as it is open in most countries worldwide.
The 802.15.4 standard specifies that communication should occur in 5MHz channels ranging
from 2.405 to 2.480 GHz. In the 2.4 GHz band a maximum over-the-air datarate of 250kbps is
specified, but due to the overhead of the protocol, the actual maximum data rate is approximately
half of that.

The 802.15.4 standard allows for communication in point-to-point or a point-to-multi-point


configuration. A typical application involves a central coordinator with multiple nodes
connecting back to this central host.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 94
ZigBee Protocol

ZigBee is a protocol that uses the 802.15.4 standard as a baseline and adds additional routing and
network functionality. The ZigBee protocol was developed by the ZigBee Alliance. ZigBee is
designed to add mesh networking to the underlying 802.15.4 radio.

Devices in the ZigBee specification can either be used as End Devices, Routers or Coordinators.
Because ZigBee was used for low power applications, it fits well into embedded systems and
those markets where reliability and versatility are important but a high bandwidth is not.

XBee
The ZigBee radios used in the lab are XBee Series 2 modules from Digi

Pin description of Xbee module

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 95
To form a network with these modules, there should one Coordinator and one or more
Routers/Endpoints

The XBee moule is made a Coordinator/Router/Endpoint by loading the appropriate firmware in


the module using a utility called X-CTU, provided by Digi.

X-CTU will also be used to make changes in the settings of the XBee modules – settings such as
PAN ID and DH/DL

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 96
XBee Modes

AT Mode/Transparent Mode: By default, XBee modules operate in Transparent Mode. When


operating in this mode, the modules act as a serial line replacement - all UART data received
through the DI pin is queued up for RF transmission. When RF data is received, the data is sent
out the DO pin.
API(Application Programming Interface) Mode: API (Application Programming Interface)
Operation is an alternative to the default Transparent Operation. The frame-based API extends
the level to which a host application can interact with the networking capabilities of the module.
When in API mode, all data entering and leaving the module is contained in frames that define
operations or events within the module.

Arduino program
1.Write a program to send a character ‘A’ to receiver for every second through Zigbee.
Transmitter code
void setup()
{Serial.begin(9600);
}
void loop()
{ Serrial.println(‘A’);
delay(1000);// pauses for one second delay
}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 97
Receiver code
void setup()
{Serial.begin(9600);
}
void loop()
{ while(Serial.available())
{
Serial.write(Serial.read());
delay(1000);// pauses for one second delay
}}

Exercises:
1.Write a Program to transfer the data Between PC1 to PC2 using ARM and Xbee
modules.

2.Write Program to Zigbee based monitoring and control system.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 98
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 99
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 100
ANALOG OUTPUTS

The Arduino Due supports the analogWrite() function for generating analog outputs. However,
the analogWrite() function uses PWM(Pulse Width Modulation) when used for pin numbers 2 to
13 and an on-chip DAC(Digital to Analog converter) when used for DAC1 and DAC2 pins.
The Due has the following hardware capabilities:
• 12 pins ( 2 to 13) with 8-bit PWM (as the other AVR based boards)
• 2 pins (DAC1 and DAC2) with 12-bit DAC (Digital-to-Analog Converter)

Pulse Width Modulation

Pulse Width Modulation, or PWM, is a technique for getting analog results with digital
means. Digital control is used to create a square wave, a signal switched between on and off.
This on-off pattern can simulate voltages in between full on (5 Volts) and off (0 Volts) by
changing the portion of the time the signal spends on versus the time that the signal spends off.
The duration of "on time" is called the pulse width. To get varying analog values, you change, or
modulate, that pulse width. If you repeat this on-off pattern fast enough with an LED for
example, the result is as if the signal is a steady voltage between 0 and 5v controlling the
brightness of the LED.
In the graphic below, the green lines represent a regular time period. This duration or
period is the inverse of the PWM frequency. In other words, with Arduino's PWM frequency at
about 500Hz, the green lines would measure 2 milliseconds each. A call toanalogWrite() is on a
scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on), and
analogWrite(127) is a 50% duty cycle (on half the time) for example.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 101
DAC
DAC1 and DAC2 pins, the 12-bit on-chip DAC is used. Due supports an additional function:
analogWriteResolution() which will help leverage the full 12-bits of the DAC

analogWriteResolution()
Description
analogWriteResolution() is an extension of the Analog API for the Arduino Due.
analogWriteResolution() sets the resolution of the analogWrite() function. It defaults to 8 bits
(values between 0-255) for backward compatibility with AVR based boards.
The Due has the following hardare capabilities:
• 12 pins with 8-bit PWM (as the other AVR based boards)
• 2 pins with 12-bit DAC (Digital-to-Analog Converter)
By setting the write resolution to 12, you can use analogWrite() with values between 0 and 4095
to exploit the full DAC resolution or to set the PWM signal without rolling over.
S yn tax
analogWriteResolution(bits)
Para met ers
bits: determines the resolution (in bits) of the values used in the analogWrite() function. The
value can range from 1 to 32. If you choose a resolution higher or lower than your board's
hardware capabilities, the value used in analogWrite() will be either truncated if it's too high or
padded with zeros if it's too low. See the note below for details.
Retu rn s
None.
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 102
Note: If you set the analogWriteResolution() value to a value higher than your board's
capabilities, the Arduino will discard the extra bits. For example: using the Due with
analogWriteResolution(16) on a 12-bit DAC pin, only the first 12 bits of the values passed to
analogWrite() will be used and the last 4 bits will be discarded.
If you set the analogWriteResolution() value to a value lower than your board's capabilities, the
missing bits will be padded with zeros to fill the hardware required size. For example: using the
Due with analogWriteResolution(8) on a 12-bit DAC pin, the Arduino will add 4 zero bits to the
8-bit value used in analogWrite() to obtain the 12 bits required.

Arduino programs
1. This example shows how to fade an LED using the analogWrite() function. Use the
GRIET LED/switches shield.

int ledPin = 9; // LED connected to digital pin 9

void setup() {
// nothing happens in setup
}

void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:


for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 103
2. The LED and switches shield are used for this exercise. The sensor connected to A0 pin
is read and this analog value(0 – 1023) is mapped to different resolutions: 8, 12 and 4 for
changing the intensity of three different LEDs.

void setup(){
// open a serial connection
Serial.begin(9600);
// make our digital pin an output
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
}

void loop(){
// read the input on A0 and map it to a PWM pin
// with an attached LED
int sensorVal = analogRead(A0);
Serial.print("Analog Read) : ");
Serial.print(sensorVal);

// the default PWM resolution


analogWriteResolution(8);
analogWrite(11, map(sensorVal, 0, 1023, 0 ,255));
Serial.print(" , 8-bit PWM value : ");
Serial.print(map(sensorVal, 0, 1023, 0 ,255));

// change the PWM resolution to 12 bits


// the full 12 bit resolution is only supported
// on the Due
analogWriteResolution(12);
analogWrite(12, map(sensorVal, 0, 1023, 0, 4095));
Serial.print(" , 12-bit PWM value : ");
Serial.print(map(sensorVal, 0, 1023, 0, 4095));

// change the PWM resolution to 4 bits


analogWriteResolution(4);
analogWrite(13, map(sensorVal, 0, 1023, 0, 127));
Serial.print(", 4-bit PWM value : ");
Serial.println(map(sensorVal, 0, 1023, 0, 127));
delay(5);
}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 104
Exercise:

Write a program to Generation of PWM Signal

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 105
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 106
Serial to Peripheral Interface (SPI) Protocol

Introduction

Serial to Peripheral Interface (SPI) is a hardware/firmware communications protocol developed


by Motorola and later adopted by others in the industry. The Serial Peripheral Interface or SPI-
bus is a simple 4-wire serial communications interface used by many
microprocessor/microcontroller peripheral chips that enables the controllers and peripheral
devices to communicate each other. Even though it is developed primarily for the
communication between host processor and peripherals, a connection of two processors via SPI
is just as well possible. The SPI bus, which operates at full duplex (means, signals carrying data
can go in both directions simultaneously), is a synchronous type data link setup with a Master /
Slave interface and can support up to 1 megabaud or 10Mbps of speed. The SPI Bus is usually
used only on the PCB. There are many facts, which prevent us from using it outside the PCB
area. The SPI Bus was designed to transfer data between various IC chips, at very high speeds.
Due to this high-speed aspect, the bus lines cannot be too long, because their reactance increases
too much, and the Bus becomes unusable.
The peripherals can be a Real Time Clocks, converters like ADC and DAC, memory modules
like EEPROM and FLASH, sensors like temperature sensors and pressure sensors, or some other
devices like signal-mixer, potentiometer, LCD controller, UART, CAN controller, USB
controller and amplifier.
Data and control lines of the SPI and the basic connection:

An SPI protocol specifies 4 signal wires.


1. Master Out Slave In (MOSI) - MOSI signal is generated by Master, recipient is the Slave.
2. Master In Slave Out (MISO) - Slaves generate MISO signals and recipient is the Master.
3. Serial Clock (SCLK or SCK) - SCLK signal is generated by the Master to synchronize data
transfers between the master and the slave.
4. Slave Select (SS) from master to Chip Select (CS) of slave - SS signal is generated by Master

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 107
to select individual slave/peripheral devices. The SS/CS is an active low signal.

As we already know, in SPI-bus communication there can be one master with multiple slaves. In
single-master protocol, usually one SPI device acts as the SPI Master and controls the data flow
by generating the clock signal (SCLK) and activating the slave it wants to communicate with
slave-select signal (SS), then receives and or transmits data via the two data lines. A master,
usually the host micro controller, always provides clock signal to all devices on a bus whether it
is selected or not.
The usage of these each four pins may depend on the devices. For example, SDI pin may not be
present if a device does not require an input (ADC for example), or SDO pin may not be present
if a device does not require an output (LCD controllers for example). If a microcontroller only
needs to talk to 1 SPI Peripheral or one slave, then the CS pin on that slave may be grounded.
With multiple slave devices, an independent SS signal is needed from the master for each slave
device.
How do they communicate?
The communication is initiated by the master all the time. The master first configures the clock,
using a frequency, which is less than or equal to the maximum frequency that the slave device
supports. The master then select the desired slave for communication by pulling the chip select
(SS) line of that particular slave-peripheral to "low" state. If a waiting period is required (such as
for analog-to-digital conversion) then the master must wait for at least that period of time before
starting to issue clock cycles.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 108
The slaves on the bus that have not been activated by the master using its slave select signal will
disregard the input clock and MOSI signals from the master, and must not drive MISO. That
means the master selects only one slave at a time.
Most devices/peripherals have tri-state outputs, which goes to high impedance state
(disconnected) when the device is not selected. Devices without this tri-state outputs cannot
share SPI bus with other devices, because such slave's chip-select may not get activated.
A full duplex data transmission can occur during each clock cycle. That means the master sends
a bit on the MOSI line; the slave reads it from that same line and the slave sends a bit on the
MISO line; the master reads it from that same line.

Data transfer is organized by using Shift register with some given word size such as 8- bits
(remember, its not limited to 8-bits), in both master and slave. They are connected in a ring.
While master shifts register value out through MOSI line, the slave shifts data in to its shift
register.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 109
Data are usually shifted out with the MSB first, while shifting a new LSB into the same register.
After that register has been shifted out, the master and slave have exchanged their register
values. Then each device takes that value and does the necessary operation with it (for example,
writing it to memory). If there are more data to be exchanged, the shift registers are loaded with
new data and the process is repeated. When there are no more data to be transmitted, the master
stops its clock. Normally, it then rejects the slave.

Significance of the clock polarity and phase:

Another pair of parameters called clock polarity (CPOL) and clock phase (CPHA) determine the
edges of the clock signal on which the data are driven and sampled. That means, in addition to
setting the clock frequency, the master must also configure the clock polarity (CPOL) and phase
(CPHA) with respect to the data.
Since the clock serves as synchronization of the data communication, there are four possible
modes that can be used in an SPI protocol, based on this CPOL and CPHA.

SPI Mode CPOL CPHA


0 0 0
1 0 1
2 1 0
3 1 1
If the phase of the clock is zero (i.e. CPHA = 0) data is latched at the rising edge of the clock
with CPOL = 0, and at the falling edge of the clock with CPOL = 1.
If CPHA = 1, the polarities are reversed. Data is latched at the falling edge of the clock with
CPOL = 0, and at the rising edge with CPOL = 1.
The micro-controllers allow the polarity and the phase of the clock to be adjusted. A
positive polarity results in latching data at the rising edge of the clock. However data is put on
the data line already at the falling edge in order to stabilize. Most peripherals, which can only be
slaves, work with this configuration. If it should become necessary to use the other polarity,
transitions are reversed.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 110
Independent slave configuration:
This is the typical SPI-bus configuration with one SPI-master and multiple slaves/peripherals. In
this independent or parallel slave configuration,
1. All the clock lines (SCLK) are connected together.
2. All the MISO data lines are connected together.
3. All the MOSI data lines are connected together.
4. But the Chip Select (CS) pin from each peripheral must be connected to a separate Slave
Select (SS) pin on the master-microcontroller.

The SAM3x8E has on-chip support for SPI.These pins support SPI communication using the The
SPI pins are broken out on the central 6-pin header. The SPI header can be used only to
communicate with other SPI devices, not for programming the SAM3X with the In-Circuit-
Serial-Programming technique.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 111
Ethernet Basics

TCP/IP basics

TCP/IP (Transmission Control Protocol / Internet Protocol ) stands for a set of protocols
and not just two protocols: TCP and IP. But as TCP and IP are the two most important protocols,
the whole set is known as TCP/IP.
Protocol: Protocol is a set of rules that must be followed by two machines in a network in order
to communicate with each other irrespective of their platforms.
TCP/IP has four layers. These layers are logical and not physical. One must understand the logic
that caused the division.
• Application Layer – Represents the application
• Transport Layer – Controls reliability of transmission
• Internet Layer – Takes care of addressing the packets
• Network Access Layer – Convert IP address into MAC address
Data originates at the application layer and then travels through all other layers. At the transport
layer, the data is broken into chunks. The chunks have different names at the different layers, but
they are universally known as datagrams. Each layer adds its own information known as header,
to the data received from the upper layer. Thus encapsulation is achieved. At the receiving end,
data goes into exactly opposite direction.
Now let’s look at the layers of TCP/IP stack in brief.
Application Layer

This layer contains various services like FTP, TELNET, DNS, NFS, HTTP. Data
originates at this layer and fed into transport layer in form of stream. Application layer doesn’t
add any header to the stream.
Services like TELNET, FTP, and HTTP uses TCP protocol while DNS, NFS uses UDP protocol.
Transport Layer

Transport layer features two protocols: TCP and UDP. TCP is a reliable and connection
oriented protocol. It provides for error detection and recovery facilities. UDP is unreliable and
connectionless protocol. It doesn’t care whether data has reached the destination or not. But UDP
is somewhat faster than TCP protocol.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 112
TCP first divides the stream received from application layer, into segments and adds its
own header. The header usually contains the information required for reliable transmission. TCP
exchanges data in a 3-way handshake. It first sends a segment, wait for a positive
acknowledgement from the transport layer of the remote machine. And after receiving
acknowledgement, it sends one acknowledgement again. After this the connection is said to be
established. Then TCP proceeds with data transfer.
Internet Layer
This layer takes care of addressing requirements. It also plays role in determining the
route of the packet to reach the destination. The main protocol in this layer is IP ( Internet
Protocol ). It often uses services of ICMP ( Internet Control Message Protocol ).
IP headers includes both, source and destination address (what we call is IP address ).
Network Access Layer
This is the last layer of acknowledgement stack. It is the layer which has knowledge of
underlying hardware. It accepts the packets from IP layer and encapsulates them after converting
all IP addresses into MAC addresses. Then it sends the data to the wire ( physical entity ).
ARP ( Address Resolution Protocol ) is the main protocol of this layer. MAC address is a set of
six colon delimited hexadecimal numbers. For example, 0:10:AB:34:1E:20. IEEE and other
international organizations have ensured the uniqueness of MAC addresses throughout the world.

Arduino Ethernet Shield

Internet connectivity for embedded devices is fast becoming an essential feature for most
embedded devices. This requires the implementation of the TCP/IP stack. The MCU of the
embedded system will be heavily burdened if it implements the TCP/IP stack. Now, hardware
chips such as Wiznet’s W5100 implement the TCP/IP stack using hardwired logic. They will
communicate with the main MCU using well-known interfaces such as SPI(Serial Peripheral
Interface). This approach will take quite a bit of networking load off the main MCU.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 113
Wiznet 5100

Hardwired TCP/IP Embedded Ethernet Controller


Features
- Supports Hardwired TCP/IP Protocols : TCP, UDP, ICMP, IPv4 ARP, IGMP,
PPPoE, Ethernet
- 10BaseT/100BaseTX Ethernet PHY embedded
- Support Auto Negotiation (Full-duplex and half duplex)
- Supports 4 independent sockets simultaneously
- Internal 16Kbytes Memory for Tx/Rx Buffers
- 3.3V operation with 5V I/O signal tolerance
- Supports Serial Peripheral Interface(SPI MODE 0, 3)

The Arduino Ethernet Shield connects your Arduino to the internet in mere minutes. Just
plug this module onto your Arduino board, connect it to your network with an RJ45 cable and
follow a few simple instructions to start controlling your world through the internet.
• Ethernet Controller: W5100 with internal 16K buffer
• Connection speed: 10/100Mb
• Connection with Arduino on SPI port

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 114
EMBEDDED WEB SERVER

Embedded web server provides service(Web pages) to the client based on request. Here
Microcontroller and Ethernet module acting as a Web server.The Arduino Ethernet Shield
allows an Arduino board to connect to the internet. It is based on the W5100 ethernet chip. The
Wiznet W5100 provides a network (IP) stack capable of both TCP and UDP. It supports up to
four simultaneous socket connections. Use the library to write sketches which connect to the
internet using the shield.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 115
Ethernet Library functions
Ethernet class
The Ethernet class initializes the ethernet library and network settings.
• begin()
• localIP()
• maintain()

Ethernet.begin()
Description
Initializes the ethernet library and network settings. With version 1.0, the library supports
DHCP. Using Ethernet.begin(mac) with the proper network setup, the Ethernet shield will
automatically obtain an IP address. This increases the sketch size significantly.
Syntax
Ethernet.begin(mac);
Ethernet.begin(mac, ip);
Ethernet.begin(mac, ip, dns);
Ethernet.begin(mac, ip, dns, gateway);
Ethernet.begin(mac, ip, dns, gateway, subnet);

Parameters
mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the
Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with
the device's MAC address. For older shields, choose your own.
ip: the IP address of the device (array of 4 bytes)
dns: the address for a DNS server.
gateway: the IP address of the network gateway (array of 4 bytes). optional: defaults to the
device IP address with the last octet set to 1
subnet: the subnet mask of the network (array of 4 bytes). optional: defaults to 255.255.255.0
Returns
The DHCP version of this function, Ethernet.begin(mac), returns an int: 1 on a successful DHCP
connection, 0 on failure. The other versions don't return anything.
IPAddress class

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 116
The IPAddress class works with local and remote IP addressing.
• IPAddress()
IPAddress()
Description
Defines an IP address. It can be used to declare both local and remote addresses.
Syntax
IPAddress(address);
Parameters
address: a comma delimited list representing the address (4 bytes, ex. 192, 168, 1, 1)
Returns
None
Server class
The Server class creates servers which can send data to and receive data from connected clients
(programs running on other computers or devices).
• Server
• EthernetServer()
• begin()
• available()
• write()
• print()
• println()
EthernetServer()
Description
Create a server that listens for incoming connections on the specified port.
Syntax
Server(port);
Parameters
port: the port to listen on (int)
Returns
None
begin()
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 117
Description
Tells the server to begin listening for incoming connections.
Syntax
server.begin()
Parameters
None
Returns
None
available()

Description
Gets a client that is connected to the server and has data available for reading. The connection
persists when the returned client object goes out of scope; you can close it by calling
client.stop().
available() inherits from the Stream utility class.
Syntax
server.available()
Parameters
None
Returns
a Client object; if no Client has data available for reading, this object will evaluate to false in an
if-statement (see the example below)
Example
#include <Ethernet.h>
#include <SPI.h>
// the media access control (ethernet hardware) address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
//the IP address for the shield:
byte ip[] = { 10, 0, 0, 177 };
// the router's gateway address:
byte gateway[] = { 10, 0, 0, 1 };
// the subnet:
byte subnet[] = { 255, 255, 0, 0 };
// telnet defaults to port 23
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 118
EthernetServer server = EthernetServer(23);
void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();}
void loop()
{
// if an incoming client connects, there will be bytes available to read:
EthernetClient client = server.available();
if (client == true) {
// read bytes from the incoming client and write them back
// to any clients connected to the server:
server.write(client.read());
}}
Client class

The client class creates clients that can connect to servers and send and receive data.
• Client
• EthernetClient()
• connected()
• connect()
• write()
• print()
• println()
• available()
• read()
• flush()
• stop()
EthernetClient()
Description
Creates a client which can connect to a specified internet IP address and port (defined in the
client.connect() function).
Syntax
EthernetClient()
Parameters
None
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 119
Example
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 10, 0, 0, 177 };
byte server[] = { 64, 233, 187, 99 }; // Google
EthernetClient client;

void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /search?q=arduino HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}

void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;);
}
}

HTTP Client-Server basics

The Hypertext Transfer Protocol (HTTP) is the application-layer protocol that


implements the World Wide Web. While the Web itself has many different facets, HTTP is only

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 120
concerned with one basic function: the transfer of hypertext documents and other files from Web
servers to Web clients. In terms of actual communication, clients are chiefly concerned with
making requests to servers, which respond to those requests.
Thus, even though HTTP includes a lot of functionality to meet the needs of clients and
servers, when you boil it down, what see is a very simple, client/server, request/response
protocol.
Basic HTTP Client/Server Communication

In its simplest form, the operation of HTTP involves only an HTTP client, usually a Web
browser on a client machine, and an HTTP server, more commonly known as a Web server.
After a TCP connection is created, the two steps in communication are as follows:
• Client Request: The HTTP client sends a request message formatted according to the
rules of the HTTP standard—an HTTP Request. This message specifies the resource that
the client wishes to retrieve, or includes information to be provided to the server.
• Server Response: The server reads and interprets the request. It takes action relevant to
the request and creates an HTTP Response message, which it sends back to the client.
The response message indicates whether the request was successful, and may also contain
the content of the resource that the client requested, if appropriate.

Figure 315: HTTP Client/Server Communication


HTML basics

The HTTP server serves up a HTML(Hyper text Markup Language) page in the simplest
form of transfer. HTML is the lingua franca of the web. It’s a simple, universal mark-up
language that allows web publishers to create complex pages of text and images that can be
viewed by anyone else on the web, regardless of what kind of computer or browser is being used.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 121
Despite what you might have heard, you don’t need any special software to create an HTML
page; all you need is a word processor (such as Microsoft Word) and a working knowledge of
HTML.
It’s All About the Tags

HTML is just a series of tags that are integrated into a text document. They’re a lot like stage
directions — silently telling the browser what to do, and what props to use.
HTML tags are usually English words (such as blockquote) or abbreviations (such as “p” for
paragraph), but they are distinguished from the regular text because they are placed in small
angle brackets. So the paragraph tag is <p>, and the blockquote tag is <blockquote>.Some tags
dictate how the page will be formatted (for instance, <p> begins a new paragraph), and others
dictate how the words appear (<b> makes text bold). Still others provide information — such as
the title — that doesn’t appear on the page itself.
The first thing to remember about tags is that they travel in pairs. Every time you use a
tag – say<blockquote> – you must also close it off with another tag – in this case, </blockquote>.
Note the slash – / – before the word “blockquote”; that’s what distinguishes a closing tag from an
opening tag.
The basic HTML page begins with the tag <html> and ends with </html>. In between, the file
has two sections – the header and the body.The header – enclosed by the <head> and </head>
tags – contains information about a page that won’t appear on the page itself, such as the title.
The body – enclosed by <body> and </body> – is where the action is. Every thing that appears
on the page is contained within these tags.
A Basic HTML Document

So let’s create a simple sample page, shall we? The first step, of course, is to create a new
text document (remember, it should be saved as “Text Only” or “Plain Text” if you’re using a
word processor that’s fancier than, say, SimpleText) and name it “myPage.html”

Your basic document will look something like this:


<html>
<head>
<title>Summer Vacation</title>
</head>
<body>
<h1>Summer Vacation</h1>
<p>My summer vacation was sunny, silly and far too short</p>
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 122
<p>How many days till Dasara?</p>
</body>
</html>
So within the <head> tags, we have the title “Summer,” which will appear in the bar
across the top of your browser.
Within the body tags, we have everything that will appear on the page. In this case it
would look something like this:

The Ethernet shield can be used to make the Arduino system, a HTTP server.

Arduino programs

1. A simple web server that shows the value of the analog input pins using an Arduino Wiznet
Ethernet shield.
The following HTML page will be displayed:
<html>
<meta http-equiv = “refresh\” context=\”5\”>
analog input 0 is xxx
analog input 1 is xxx
analog input 2 is xxx
analog input 3 is xxx
analog input 4 is xxx
analog input 5 is xxx
<\html>
Meta refresh is a method of instructing the web browser to automatically refresh the current web
page after a given time interval

#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0x90, 0xA2, 0xDA, 0x0D, 0xA5, 0xF0 };
IPAddress ip(192,168,11,177);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 123
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) { //IF1
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) { //WHILE
if (client.available()) { //IF2
char c = client.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) { //IF3
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// add a meta refresh tag, so the browser pulls again every 5 seconds:
client.println("<meta http-equiv=\"refresh\" content=\"5\">");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) { //FOR
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}//FOR ENDS
client.println("</html>");
break;
} //IF3 ENDS
if (c == '\n') { //IF4
// you're starting a new line
currentLineIsBlank = true;
} //IF4
else if (c != '\r') { //ELSE IF
// you've gotten a character on the current line
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 124
currentLineIsBlank = false;
} // ELSE IF ENDS
} //IF2 ENDS
} //WHILE ENDS

// give the web browser time to receive the data


delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
} //IF1 ENDS
} //LOOP ENDS

2. DHCP-based IP printer: This sketch uses the DHCP extensions to the Ethernet library
to get an IP address via DHCP and print the address obtained using an Arduino Wiznet
Ethernet shield.

#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {0x90, 0xA2, 0xDA, 0x0D, 0xA5, 0xF0};
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// this check is only needed on the Leonardo:
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}

// start the Ethernet connection:


if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
for(;;);
}
// print your local IP address:
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 125
}
Serial.println();
}
void loop() {
}

3. Internet based LED control

To turn it on:
http://your-IP-address/$1

To turn it off:
http://your-IP-address/$2
#include <SPI.h>
#include <Ethernet.h>
boolean incoming = 0;
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0xA5, 0xF0 };
IPAddress ip(192,168,98,111); //<<< ENTER YOUR IP ADDRESS HERE!!!
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup()
{
pinMode(2, OUTPUT);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.begin(9600);
}

void loop()
{
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 126
//reads URL string from $ to first blank space
if(incoming && c == ' '){
incoming = 0;
}
if(c == '$'){
incoming = 1;
}
//Checks for the URL string $1 or $2
if(incoming == 1){
Serial.println(c);
if(c == '1'){
Serial.println("ON");
digitalWrite(2, HIGH);
}
if(c == '2'){
Serial.println("OFF");
digitalWrite(2, LOW);
}
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}}}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}}
Exercise:

Program to implement the Embedded Web Server using Ethernet module (temperature and LDR
readings on webpage when corresponding button is pressed[ background color is green, text
color is red].

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 127
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 128
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 129
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 130
SD CARD Module

We use the Arduino Ethernet shield to demonstrate the working of SPI. This shield has an
Ethernet chip and an SD card slot. Both the Ethernet chip and the on-board SD card reader work
on the SPI interface. We will be dealing with the Ethernet chip in a later chapter. The SD card
interface is done using the SD library functions. This in turn uses the SPI library functions. The
SS(Slave Select) pin for the SD card is pin 4 on the shield.

The SD library allows for reading from and writing to SD cards, e.g. on the Arduino
Ethernet Shield. The library supports FAT16 and FAT32 file systems on standard SD cards and
SDHC cards. It uses short 8.3 names for files.
Formatting/Preparing the card
(NB : whenever referring to the SD card, it means SD and microSD sizes, as well as SD and
SDHD formats).You’ll need a SD reader and computer to format your card properly. The library
supports the FAT16 and FAT32filesystems, but use FAT16 when possible. The process to
format is fairly straightforward.
Windows: right click on your card’s directory and choose “Format” from the drop down. Make
sure you choose FAT as the filesystem.
File Naming
FAT file systems have a limitation when it comes to naming conventions. You must use
the 8.3 format, so that file names look like “NAME001.EXT”, where “NAME001” is an 8
character or fewer string, and “EXT” is a 3 character extension. People commonly use the
extensions .TXT and .LOG. It is possible to have a shorter file name (for example, mydata.txt, or
time.log), but you cannot use longer file names.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 131
SD card Library functions
begin()
Description
Initializes the SD library and card. Note that even if you use a different chip select pin,
the hardware SS pin must be kept as an output for the SD library functions to work.
Syntax
SD.begin()
SD.begin(cspin)
Parameters
cspin (optional): the pin connected to the chip select line of the SD card; defaults to the hardware
SS line of the SPI bus
Returns
true on success; false on failure

open()
Description
Opens a file on the SD card. If the file is opened for writing, it will be created if it doesn't
already exist (but the directory containing it must already exist).
Syntax
SD.open(filepath)
SD.open(filepath, mode)
Parameters
filename: the name the file to open, which can include directories (delimited by forward slashes,
/) - char *
mode (optional): the mode in which to open the file, defaults to FILE_READ - byte. one of:
FILE_READ: open the file for reading, starting at the beginning of the file.
FILE_WRITE: open the file for reading and writing, starting at the end of the file.
Returns
a File object referring to the opened file; if the file couldn't be opened, this object will
evaluate to false in a boolean context, i.e. you can test the return value with "if (f)".
close()
Close the file, and ensure that any data written to it is physically saved to the SD card.
Syntax
file.close()
Parameters
file: an instance of the File class (returned by SD.open())
Returns
none

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 132
write()
Description
Write data to the file.
Syntax
file.write(data)
file.write(buf, len)
Parameters
file: an instance of the File class (returned by SD.open())
data: the byte, char, or string (char *) to write
buf: an array of characters or bytes
len: the number of elements in buf
Returns
byte
write() will return the number of bytes written, though reading that number is optional
read()
Read a byte from the file.
read() inherits from the Stream utility class.
Syntax
file.read()
Parameters
file: an instance of the File class (returned by SD.open())
Returns
The next byte (or character), or -1 if none is available.
available()
Check if there are any bytes available for reading from the file.
available() inherits from the Stream utility class.
Syntax
file.available()
Parameters
file: an instance of the File class (returned by SD.open())
Returns:the number of bytes available (int)
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 133
Arduino programs
• This example shows how to read and write data to and from an SD card file
#include <SPI.h>
#include <SD.h>
File myFile;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
// re-open the file for reading:
myFile = SD.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}}
void loop()
{// nothing happens after setup }

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 134
2. SD card datalogger: This example shows how to log data from three analog sensors
to an SD card using the SD library.
#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
}
void loop()
{
// make a string for assembling the data to log:
String dataString = "";
// read three sensors and append to the string:
for (int analogPin = 0; analogPin < 3; analogPin++) {
int sensor = analogRead(analogPin);
dataString += String(sensor);
if (analogPin < 2) {
dataString += ",";
}
}
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 135
Exercise

Write a Program for reading and writing of a file.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 136
AUDIO

The Audio library enables an Arduino Due board to play back .wav files from a storage
device like an SD card.
The Due uses the DAC0 and DAC1 pins to play sounds.
Functions
• begin()
• prepare()
• write()
begin()
Description
Initializes the Audio library by specifying the target sample rate and size of the audio buffer.
Syntax
Audio.begin(rate, size);
Parameters
rate (int): the sample rate of the sound file. If stereo, double the rate (ex. 44100hz stereo =
88200).
size (int): the size of the audio buffer in milliseconds.
Returns
Nothing
prepare()
Description
Prepares audio samples from the named file to the audio buffer, and sets the volume.
Syntax
Audio.prepare(buffer, samples, volume);
Parameters
buffer (short): the named buffer holding the audio file.
samples (int): number of samples to write
volume (int): a 10-bit number representing the volume of the audio being played. 0 turns
the sound off, 1023 is the maximum volume.
Returns :Nothing

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 137
write()
Description
Writes an audio signal from a buffer to DAC0 and DAC1.
Syntax
Audio.write(buffer, length);
Parameters
buffer (short) : the named buffer with the audio file.
length (int) : number of samples to write
Returns
Nothing

Arduino program:

1.This program uses the Arduino Ethernet Shield. This shield has an SD card that can be
used to store a song in the .wav format. The interface between the SD card and the Due is
over SPI. The Audio library functions are used to play the song

#include <SD.h>
#include <SPI.h>
#include <Audio.h>
void setup()
{
// debug output at 9600 baud
Serial.begin(9600);
// setup SD-card
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println(" failed!");
return;
}
Serial.println(" done.");
// hi-speed SPI transfers
SPI.setClockDivider(4);
// 44100Khz stereo => 88200 sample rate
// 100 mSec of prebuffering.
Audio.begin(88200, 100);
}
void loop()
{
int count=0;

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 138
// open wave file from sdcard
File myFile = SD.open("test.wav");
if (!myFile) {
// if the file didn't open, print an error and stop
Serial.println("error opening test.wav");
while (true);
}
const int S=1024; // Number of samples to read in block
short buffer[S];
Serial.print("Playing");
// until the file is not finished
while (myFile.available()) {
// read from the file into buffer
myFile.read(buffer, sizeof(buffer));
// Prepare samples
int volume = 1024;
Audio.prepare(buffer, S, volume);

// Feed samples to audio


Audio.write(buffer, S);
// Every 100 block print a '.'
count++;
if (count == 100) {
Serial.print(".");
count = 0;
}
}
myFile.close();
Serial.println("End of file. Thank you for listening!");
while (true) ;
}

Exercise:

• Program to interface SDcard module ,Bluetooth module and speaker with ARM and play
the songs based on commands from Android Mobile.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 139
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 140
USB Host

Standard USB uses a master/slave architecture; a host acts as the master device for the entire bus,
and a USB device acts as the slave. Devices are designed from the start to act in one role or the
other - computers are generally set up to be hosts, while printers (for instance) are normally
slaves.

When a device is plugged into the USB bus, the master device, or host, sets up communications
with the device and handles service provisioning. The host is responsible for all data transfers
over the bus, with the devices only able to signal that they require attention. To transfer data
between two devices, from a phone to a printer for instance, the host first reads the data from one
device then writes it to the other. This allows the devices to be greatly simplified compared to the
host; a mouse, for instance, contains very little logic and relies on the host to do almost all of the
work.

While the master/slave arrangement works for some devices, there are many devices that might
want to act as a master or a slave depending on who else shares the bus. For instance, a computer
printer is normally a slave device, but when a USB flash drive of images is plugged into the USB
port of the printer with no computer present (or at least turned off) it would be useful for the
printer to take on the role of host, allowing it to communicate with the flash drive directly and
print images from it.

USB On-The-Go introduces the concept that a device can perform both the master and slave
roles, and so subtly changes the terminology. With OTG, a device can be either a host when
acting as the link master, or a peripheral when acting as the link slave.

USB On-The-Go, often abbreviated USB OTG or just OTG, is a specification that allows USB
devices such as digital audio players or mobile phones to act as a host, allowing other USB
devices like a USB flash drive, mouse, or keyboard to be attached to them. Unlike conventional
USB systems, USB OTG systems can drop the hosting role and act as normal USB devices when
attached to another host. This can be used to allow a mobile phone to act as host for a flash drive
and read its contents, downloading music for instance, but then act as a flash drive when plugged
into a host computer and allow the host to read off the new content.

The SAM3X8E microcontroller in the Arduino Due has on chip support for USB-On-The-Go.
The USBHost library provided in Arduino 1.5 allows an Arduino Due board to appear as a USB
host, enabling it to communicate with peripherals like USB mice and keyboards. USBHost does
not support devices that are connected through USB hubs.
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 141
USBHost

Des cri p ti on
USBHost is the base class for all calls that rely on USB host communication. When invoked, it
initializes a USB controller.

Syntax
USBHost usb;

Task()
Description
Task() polls connected usb devices for updates to their status.
NB : If there is no activity on a connected USB device, task() will block all other calls for 5
second intervals.

Syntax
usb.Task()
P aram et ers
usb : the name of the USB controller object

USB mouse interface

MouseController
Des cri p ti on
MouseController is the class for all calls to the USBHost relating to an attached mouse.
Syntax
MouseController mouse(usb);
Using a USBno OTG cable, a USB mouse is connected to the native USB port on the Arduino
Due.

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 142
USB Mouse interface
Arduino code
// Require mouse control library
#include <MouseController.h>
// Initialize USB Controller
USBHost usb;
// Attach mouse controller to USB
MouseController mouse(usb);
// variables for mouse button states
boolean leftButton = false;
boolean middleButton = false;
boolean rightButton = false;
// This function intercepts mouse movements
void mouseMoved() {
Serial.print("Move: ");
Serial.print(mouse.getXChange());
Serial.print(", ");
Serial.println(mouse.getYChange());
}

// This function intercepts mouse movements while a button is pressed


void mouseDragged() {
Serial.print("DRAG: ");
Serial.print(mouse.getXChange());
Serial.print(", ");
Serial.println(mouse.getYChange());
}

// This function intercepts mouse button press


void mousePressed() {
Serial.print("Pressed: ");
if (mouse.getButton(LEFT_BUTTON)){
Serial.print("L");
leftButton = true;

if (mouse.getButton(MIDDLE_BUTTON)){
Serial.print("M");
middleButton = true;
}
if (mouse.getButton(RIGHT_BUTTON)){
Serial.print("R");
Serial.println();
rightButton = true;
}
}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 143
// This function intercepts mouse button release
void mouseReleased() {
Serial.print("Released: ");
if (!mouse.getButton(LEFT_BUTTON) && leftButton==true) {
Serial.print("L");
leftButton = false;
}
if (!mouse.getButton(MIDDLE_BUTTON) && middleButton==true) {
Serial.print("M");
middleButton = false;
}
if (!mouse.getButton(RIGHT_BUTTON) && rightButton==true) {
Serial.print("R");
rightButton = false;
}
Serial.println();
}

void setup()
{
Serial.begin(9600);
Serial.println("Program started");
delay(200);
}

void loop()
{
// Process USB tasks
usb.Task();
}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 144
USB keboard interface
KeyboardController

// Require keyboard control library


#include <KeyboardController.h>
// Initialize USB Controller
USBHost usb;
// Attach keyboard controller to USB
KeyboardController keyboard(usb);
// This function intercepts key press
void keyPressed() {
Serial.print("Pressed: ");
printKey();
}
// This function intercepts key release
void keyReleased() {
Serial.print("Released: ");
printKey();
}
void printKey() {
// getOemKey() returns the OEM-code associated with the key
Serial.print(" key:");
Serial.print(keyboard.getOemKey());
// getModifiers() returns a bits field with the modifiers-keys
int mod = keyboard.getModifiers();
Serial.print(" mod:");
Serial.print(mod);
Serial.print(" => ");
if (mod & LeftCtrl)
Serial.print("L-Ctrl ");
if (mod & LeftShift)
Serial.print("L-Shift ");
if (mod & Alt)
Serial.print("Alt ");
if (mod & LeftCmd)
Serial.print("L-Cmd ");
if (mod & RightCtrl)
Serial.print("R-Ctrl ");
if (mod & RightShift)
Serial.print("R-Shift ");
if (mod & AltGr)
Serial.print("AltGr ");
if (mod & RightCmd)
Serial.print("R-Cmd ");

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 145
// getKey() returns the ASCII translation of OEM key
// combined with modifiers.
Serial.write(keyboard.getKey());
Serial.println();
}
void setup()
{
Serial.begin(115200);
Serial.println("Program started");
delay(200);
}
void loop()
{
// Process USB tasks
usb.Task();
}

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 146
EXERCISES

GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19


Page 147
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 148
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 149
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 150
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 151
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 152
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 153
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 154
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 155
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 156
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 157
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 158
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 159
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 160
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 161
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 162
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 163
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 164
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 165
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 166
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 167
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 168
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 169
GRIET-ECE-M.TECH-EMBEDDED SYSTEMS-SEM I-MICROCONTROLLERS LAB MANUAL 2018-19
Page 170

You might also like