Professional Documents
Culture Documents
(Autonomous)
MICROCONTROLLERS LAB
(Autonomous)
MICROCONTROLLERS LAB
Name:
Reg. No.:
Branch:
Class:
Reg.No.___________________ in the“Microcontrollers
Note:
List of Experiments:
1.Program to configure and control General Purpose Input/Output (GPIO)port pins of ARM.
3.Program to get analog input from Temperature sensor and display the temperature value on PC.
11.Program to Interface SD card module with ARM to produce Audio output on speaker.
HARDWARE:
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
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.
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:
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.
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.
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.
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
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.
• 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
Pinout Diagram
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.
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
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
• 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
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.
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
}
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()
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'
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.
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 devices are particularly well suited for networking applications: industrial and
home/building automation, gateways.
Memories
▪ 256 to 512 Kbytes embedded Flash, 128-bit wide access, memory
accelerator, dual bank
System
▪ Embedded voltage regulator for single supply operation
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.
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
Stack Pointer:The Stack Pointer (SP) is register R13. In Thread mode, bit[1] of the CONTROL
register indicates the stack pointer to use:
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.
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
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
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
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
• 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
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.
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.
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
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.
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);}
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)
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.
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.
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.
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.
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
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.
0 = No effect.
0 = No character has been received since the last read of the UART_RHR or
the receiver is disabled.
1 = There is no character written to UART_THR not yet transferred to the Shift Register.
1 = At least one overrun error has occurred since the last RSTSTA.
1 = At least one framing error has occurred since the last RSTSTA.
1 = At least one parity error has occurred since the last RSTSTA.
1 = There are no characters in UART_THR and there are no characters being processed by the
transmitter.
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 .
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
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
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
void setup(){
Serial.begin(9600);
void loop(){
Serial.print("Time: ");
time = micros();
Serial.println(time);
delay(1000);
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)
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
}
attachInterrupt()
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);
Parameters
interrupt: the number of the interrupt (int)
mode:
defines when the interrupt should be triggered. Four contstants
are predefined as valid values:
void setup() {
pinMode(pin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE
);
}
void loop() {
digitalWrite(pin, state);
}
void blink() {
state = !state;
}
Uno, Ethernet 2 3
Mega2560 2 3 21 20 19 18
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().
Description
Syntax
detachInterrupt(interrupt)
detachInterrupt(digitalPinToInterrupt(pin));
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
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)
Schematic
1. This program reads the analog input at A1 and displays it in the Serial Monitor
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.
Pin-out &Schematic
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.
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).
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
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
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:
void setup()
Serial.begin(9600);
Serial1.begin(9600);
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);
Exercise
Write a Program to implement RFID based access control system
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
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println(““Microcontrollers lab”);
delay(1000);}
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
Schematic
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
X-CTU will also be used to make changes in the settings of the XBee modules – settings such as
PAN ID and DH/DL
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
}
Exercises:
1.Write a Program to transfer the data Between PC1 to PC2 using ARM and Xbee
modules.
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, 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.
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.
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);
}
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);
Introduction
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.
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.
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.
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.
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.
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.
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
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.
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
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(;;);
}
}
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.
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.
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”
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
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
}
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].
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.
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
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
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;
Exercise:
• Program to interface SDcard module ,Bluetooth module and speaker with ARM and play
the songs based on commands from Android Mobile.
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
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.
if (mouse.getButton(MIDDLE_BUTTON)){
Serial.print("M");
middleButton = true;
}
if (mouse.getButton(RIGHT_BUTTON)){
Serial.print("R");
Serial.println();
rightButton = true;
}
}
void setup()
{
Serial.begin(9600);
Serial.println("Program started");
delay(200);
}
void loop()
{
// Process USB tasks
usb.Task();
}