By Kashif
WHAT IS A
MICROCONTROLLER?
• A small computer on a single chip
• containing a processor, memory, and input/output
• Typically "embedded" inside some device that they
control
• A microcontroller is often small and low cost
WHAT IS A DEVELOPMENT
BOARD?
A printed circuit board
designed to facilitate work
with a particular
microcontroller.
• Typical components include:
• power circuit
• programming interface
• basic input; usually buttons and LEDs
• I/O pins
THE MANY FLAVORS OF
ARDUINO
• Arduino Uno
• Arduino Leonardo
• Arduino LilyPad
• Arduino Mega
• Arduino Nano
• Arduino Mini
• Arduino Mini Pro
• Arduino BT
Digital I/O Pins
Analog Pins with ~ are PWM
Reference [Analog Output] Transmitter/Receiver
GND
Serial Connection
USB
Reset Button
Microcontroller ATmega328
Operating Voltage 5V
Input Voltage (recommended)7-12V
Input Voltage (limits)6-20V
Digital I/O Pins 14
(of which 6 provide PWM output)
Analog Input Pins 6
DC Current per I/O Pin 40 mA
DC Current for 3.3V Pin 50 mA
7-12v External
Adapter 16Mhz DC input 5
Crystal Analog Input Pins
Supplies
--- Arduino IDE ---
Programming and
Simulation Environment
Check out:
http://arduino.cc/en/Guide/HomePage
1. Download & install the Arduino environment
(IDE) (not needed in lab)
2. Connect the board to your computer via the
USB cable
3. If needed, install the drivers (not needed in
lab)
4. Launch the Arduino IDE
5. Select your board
6. Select your serial port
7. Open the blink example
8. Upload the program
See: http://arduino.cc/en/Guide/Environment for more information
todbot.com/blo/bionicarduino
Lets Discuss Arduino
Code Basics and Digital I/O
programming
ARDUINO
PROGRAM
SKETCH
STRUCTURE void setup() {
// put your setup code here, to run once
//The setup section is used for assigning
TWO functions Used
input and outputs (Examples: motors,
LED’s, sensors etc) to ports on the
• void setup() Arduino
– Will be executed
only when the //setup motors, sensors etc
program begins
(or reset button }
is pressed)
void loop() {
// put your main code here, to run
• void loop() repeatedly
– Will be executed // e.g get information from sensors
repeatedly // send commands to motors etc
}
ARDUINO COMMANDS TO CONFIGURE I/O
DIRECTION AND DATA
pinMode(pin#, mode) // command to make pin#9 of
Sets pin mode to either INPUT or OUTPUT Arduino as OUTPUT
pinMode(9, OUTPUT);
digitalWrite(pin#,value)
Writes HIGH or LOW value to a pin // command to write LOW to pin#2
digitalWrite(2, LOW);
digitalRead(pin#)
Reads HIGH or LOW from a pin
// Code to make pin#1 HIGH if pin#2 is LOW
if(digitalRead(2) == LOW)
{
digitalWrite(1, HIGH);
}
Program that toggle LED after every ½ sec
attatched with pin 13 of Arduino
const int kPinLed = 13;
void setup() //will run once in start
{
pinMode(kPinLed, OUTPUT); //make pin#13 o/p
}
void loop() //executed again and again
{
digitalWrite(kPinLed, HIGH); //make pin#13 hi
delay(500); //500ms delay, command format:
delay(milliseconds)
digitalWrite(kPinLed, LOW); //make pin#13 lo
delay(500);
}
Program that switch on LEDs connected to pin2-5 from left to right
and then switch off on reverse order
const int kPinLeds[] = {2,3,4,5}; // LEDs connected to pins 2-5
void setup()
{
for(int i = 0; i<4; i++)
pinMode(kPinLeds[i], OUTPUT); // make LED pins 2-5 o/p
}
void loop()
{
for(int i = 0; i < 4; i++) // LEDs switch on from left to right
{
digitalWrite(kPinLeds[i], HIGH);
delay(100);
}
for(int i = 3; i >= 0; i--) // LED switch off from right to left
{
digitalWrite(kPinLeds[i], LOW);
delay(100);
}
}
const int kPinLed = 13;
void setup()
{
pinMode(kPinLed, OUTPUT);
}
int delayTime = 1000;
void loop()
{
if(delayTime <= 100){
delayTime = 1000; // If it is less than or equal to !!100, reset it
}
else{
delayTime = delayTime - 100;
}
digitalWrite(kPinLed, HIGH);
delay(delayTime);
digitalWrite(kPinLed, LOW);
delay(delayTime);
)
Program that switch on LEDs connected to pin9 according
to switch connected on pin2
const int kPinButton1 = 2; // button attached to pin#2
const int kPinLed = 9; // LED attached with pin#9
void setup()
{
pinMode(kPinButton1, INPUT); // make button pin i/p
digitalWrite(kPinButton1, HIGH);// enable internal pull up resistors for
i/p pin
pinMode(kPinLed, OUTPUT); // make LED pins 2-5 o/p
void loop()
{
if(digitalRead(kPinButton1) == LOW) // make LED pins 2-5 o/p
digitalWrite(kPinLed, HIGH); // make LED pins 2-5 o/p
else
digitalWrite(kPinLed, LOW);
}
boolean data type is used
to store state of a pin.
ADC of Arduino
• Analog read Get binary number against
voltage given at particular analog channels
• Analog Write generate PWM of different duty
cycles at particular PWM pin
• This is not part of ADC, Just a function to
achieve a specific task!
ADC INTRO • Six analog input channels:
A0, A1, A2, A3, A4, A5
• AREF = Reference voltage
(default = +5 V)
• 10 bit resolution:
– Returns an integer from 0 to 1023
– Result is proportional to the pin
voltage
– Formulas for finding a binary
number against any voltage i/p are
same as studied in PIC
microcontrollers
• All voltages are measured
relative to GND
ARDUINO COMMAND TO READ
ADC VALUE
• analogRead(pin)
Convert analog input to a value between 01023
// code to assign a 10-bit binary number to voltage
signal given at channel A0 and store in variable integer.
int Val;
Val=analogRead(A0) ;
Application: Controlling delay using potentiometer.
Program that blink LEDs connected to pin#13, delay is
controlled through a POTENTIOMETER (used as sensor)
connected to analog channel0
int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT:
}
void loop() {
sensorValue = analogRead(sensorPin); // read the value from the sensor:
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(sensorValue); // stop the program for <sensorValue> milliseconds:
digitalWrite(ledPin, LOW); // turn the ledPin off:
delay(sensorValue); // stop the program for for <sensorValue> milliseconds:
}
ANALOG OUTPUT
Can a digital device produce analog output?
• Analog output can be simulated using
Pulse width modulation (PWM) which is
also used to control motor parameters
PULSE WIDTH MODULATION
• Can’t use digital pins
to directly supply say
2.5V, but can pulse
the output on and off
really fast to produce
the same effect
• The on-off pulsing
happens so quickly,
the connected output
device “sees” the
result as a reduction
in the voltage
output voltage = (on_time / cycle_time) * 5V
ARDUINO COMMANDS TO WRITE ANALOG
VALUE
analogWrite(pin,value)
value is duty cycle: between 0 and 255
// Command for a 50%
duty cycle on pin9
analogWrite(9, 128)
// Command for a 25%
duty cycle on pin11
analogWrite(11, 64)
PROGRAM TO CONTROL BRIGHTNESS OF LED ATTACHED
WITH PIN9 USING POTENTIOMETER ATTACHED WIT A0
const int kPinPot = A0; // POT connected
const int kPinLed = 9; //LED at pin9
void setup()
{
pinMode(kPinPot, INPUT);
pinMode(kPinLed, OUTPUT);
}
Map function Re-maps a number from one range to
another. Its format is:
void loop() map(value, fromLow, fromHigh, toLow, toHigh);
{
int ledBrightness;
int sensorValue = 0; // initialize
sensorValue = analogRead(kPinPot);
ledBrightness = map(sensorValue, 0, 1023, 0,
255); //map function is used to map value of two different
ranges, here it maps value b/w 01023 of variable
sensorValue to value between 0255
analogWrite(kPinLed, ledBrightness);
SERIAL COMMUNICATION
SERIAL
COMMUNICATIO
N
• Compiling turns your program into
binary data (ones and zeros)
• Uploading sends the bits through
USB cable to the Arduino
• The two LEDs near the USB
connector blink when data is
transmitted
• RX blinks when the Arduino is
receiving data
• TX blinks when the Arduino is
transmitting data
SERIAL MONITOR TO SEE
WHAT YOU RECEIVE ON
SCREEN
ARDUINO COMMAND TO WRITE DATA
Serial.begin(baud);
Initialize serial port for communication and sets baud rate
Example: Serial.begin(9600); // opens serial port, sets data rate to
9600 bps
Serial.print(Val) , Serial.print(Val,format)
Send data on serial port.
Examples:
Serial.print(“hi”); // print a string on screem
Serial.print(78); //works with numbers too
Serial.print(variable) //works with variables
Serial.print(78,BIN) //will send 10011110 , others formats can be
HEX,OCT
Serial.println(val); // Same as Serial.print(), but with line-feed
Program that transmit digital value of a sensor
(Potentiometer in this case) attatched to A1
int analogPin = A1; // potentiometer connected to analog channel 1
int val = 0; // variable to store the value read
void setup()
{
Serial.begin(9600); // setup serial baud rate
//write a command here to make A1 as input
}
void loop()
{
val = analogRead(analogPin); // read the sensor value
Serial.println(val); // transmit value
}
ARDUINO COMMAND TO RECEIVE DATA
Serial.read();
Returns data received
Serial.available(Val);
Returns the number of bytes in the buffer
//code to read data and store in a character
if (Serial.available() > 0) {
char data = Serial.read();
}
Serial.flush(); // clears the buffer
Some More Useful Functions, Understand your
self (Optional)
Program that receive a number through serial port and
then transmit a msg and at last transmit received
number in decimal
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to
9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
incomingByte = Serial.read(); // read the incoming byte:
// display on screen what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
ARDUINO
PROGRAMMING
WITH SENSORS,
MOTORS AND
EXTERNAL
INTERRUPTS
CONTROLLING
MOTORS USING
ARDUINO
DigitalOutput-Motion-Servo Motor
Servo Motors are electronic devices
that convert digital signal to
rotational movement.
Functions to control Servo motor:
•Servo servoname; // used to name a servo
•attach(pin); //PWM pins are used , Fucntion called through servoname
•write(angle) //called through servoname
•read() //called through servoname, return current servo angle
•detach(); //detach servo. Pins can be used for PWM
40
Standard Servo Rotation to Exact Angel
//Code to rotate a servo motor attached with pin#9 in clock and anticlockwise direction continuosly
#include <Servo.h> //servo function library
Servo myservo; // create servo object to control a servo.
int pos = 0; // variable to store the servo position
void setup()
{ myservo.attach(9); // attaches the “myservo” on pin 9 to the servo object
}
void loop()
{ myservo.attach(9); //command to tell where “myservo” is attached
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell “myservo” to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
myservo.detach(); //Detach the myservo if you are not controling it for a while
delay(2000);
} 41
STEPPER MOTORS
Motor controlled by a series of electromagnetic coils.
The coils are alternately given current or not, creating
magnetic fields which repulse or attract the magnets on the
shaft, causing the motor to rotate.
Allows for very precise control of the motor. It can be
turned in very accurate steps of set degree increments
Functions to control Stepper motor:
•Stepper motorname(steps, pin1, pin2, pin3, pin4)
•setSpeed(rpm) //called through motorname
•step(steps) // called through motorname
STEPPER MOTOR
CONTROL
//code to rotate motor attached with pin 8,9,10,11, rpm=60 and 200
steps/rev
#include <Stepper.h> //the control sequence is in this library
const int stepsPerRevolution = 200; // motor-dependent
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); //pins used
void setup() {
// set the speed at 60 rpm:
myStepper.setSpeed(60); //actually sets the delay between steps
}
void loop() {
// step one revolution in one direction:
myStepper.step(stepsPerRevolution);
delay(500);
}
USING EXTERNAL
INTERRUPTS
USING EXTERNAL
INTERRUPTS
On a UNO Arduino board, two pins can be used as interrupts: pins 2
and 3. and in MEGA these pins are used:2, 3, 18, 19, 20, 21
The interrupt is enabled through the following line:
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
modes are LOW, HIGH, RISING, FALLING, CHANGE
E.g
attachInterrupt(digitalPinToInterrupt(0), doEncoder, FALLING);
//Interrupt will occur on FALLING edge and doEncoder function called when
falling edge occurs at pin 0
INTERRUPT
changes.
EXAMPLE
//code to toggle LED status attached with PIN9 whenever pin 1 status
int led = 9;
volatile int state = LOW;
void setup()
{
pinMode(led, OUTPUT);
attachInterrupt(digitalPinToInterrupt(1), blink, CHANGE);
//PIN 1 for Intr , blink function called when change on pin 1 occurs
}
void loop()
{
digitalWrite(led, state);
}
void blink()
{
state = !state;
}
SENSO
RS!
Sound-Piezo Sensor
A Piezo is an electronic piece that converts electricity
energy to sound.
It is a digital output device.
You can make white noise or even exact musical notes
(frequencies for musical notes) based on the duration that
you iterate between HIGH and LOW signals.
48
Arduino- Digital Output-Sound-Piezo
// Program to play musical tones using piezo sensor
attached with pin 13
int freqs[] = {1915, 1700, 1519, 1432, 1275, 1136, 1014,
956};
void setup(){
pinMode(13,OUTPUT);
}
void loop(){
for(int i=0;i<8;i++) //iterating through notes
{
for(int j=0;j<1000;j++) //the time span that each
note is being played
{
digitalWrite(13,HIGH);
delayMicroseconds(freqs[i]); //delay in
microseconds
digitalWrite(13,LOW);
49
delayMicroseconds(freqs[i]);
ULTRA SONIC SENSOR
ASSIGNMENT
Using Ultra Sonic Sensor, Measure distance
of an object and display it on serial port?
Approach:
1.Understand how this sensor works
2.Understand mathematical sense of pulse generated by
this sensor
3.Understand pulseIn() function , it will help you to get
pulse width
4.Code it and test it in proteus
ULTRA SONIC SENSOR INTRO
It emits an ultrasound at 40000 Hz which
travels through the air and if there is an
object or obstacle on its path, It will
bounce back to the module.
It has 4 pins
Ground, VCC, Trig and Echo
51
ULTRA SONIC SENSOR WORKING
To generate the ultrasound you
need to do:
1. Set the Trig on a High State
for 10 µs.
2. That will send out an 8
cycle sonic burst which will
travel at the speed sound
and it will be received in
the Echo pin.
3. The Echo pin will output
the time in microseconds
the sound wave traveled
from TX to RX
52
How to measure distance?
Speed of the sound is 340 m/s or
0.034 cm/µs
Below is an example for distance=
10cm
In Arduino function
pulseIn(pin#,value) is used to
measure width of pulse in
microseconds. Value is HIGH or
LOW. i.e starting point of pulse!
53
void loop() {
// Clears the trigPin
Scenerio: Trigger pin of ultrasonic sensor is digitalWrite(trigPin, LOW);
attached with pin9 and echo with pin 10 of delayMicroseconds(2);
Arduino. On serial port throw the distance of // Sets the trigPin on HIGH state for
an object that comes in range of this 10us
sensor? digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// defines pins numbers
const int trigPin = 9; // Reads the pulse width of echoPin, i.e
const int echoPin = 10; returns the sound wave travel time in
us
// defines variables duration = pulseIn(echoPin, HIGH);
long duration;
int distance; // Calculating the distance
distance= duration*0.034/2;
void setup() {
pinMode(trigPin, OUTPUT); // trigPin as an o/p // Prints the distance on the Serial
pinMode(echoPin, INPUT); // echoPin as an i/p monitor
Serial.begin(9600); // Starts the serial comm Serial.print("Distance: ");
} Serial.println(distance);
}
INTERNET OF
THINGS
SENDING DATA
THROUGH WIFI
ESP8266 WIFI
MODULE AND
CONNECTIONS WITH
ARDUINO
• Tx and Rx pins of ESP8266
are directly connected to
pin 2 and 3 of Arduino.
• Software Serial Library is
used to allow serial
communication on pin 2
and 3 of Arduino.
MAIN STEPS TO MAKE
CONNECTION
1. Connect our wi-fi module to wi-fi router for network
connectivity
2. Then we will configure the local server
3. Send the data to web
4. Finally close the connection
LETS DISCUSS DETAILS OF
THESE STEPS!
STEP 1: Connect our wi-fi module to wi-fi
router for network connectivity
INSIDE
STEP 1:
1. First we need to test the Wi-Fi module by sending AT command, it will revert
back a response containing OK.
2. After this, we need to select mode using command AT+CWMODE=mode_id ,
we have used Mode id =3. Mode ids:
1 = Station mode (client)
2 = AP mode (host)
3 = AP + Station mode (Yes, ESP8266 has a dual mode!)
3. Now we need to disconnect our Wi-Fi module from the previously connected
Wi-Fi network, by using the command AT+CWQAP, as ESP8266 is default auto
connected with any previously available Wi-Fi network
4. After that, user can Reset the module with AT+RST command. This step is
optional.
5. Now we need to connect ESP8266 to Wi-Fi router using given command
AT+CWJAP=”wifi_username”,”wifi_password”
MAIN STEPS TO MAKE
CONNECTION
6. Now get IP Address by using given command:
AT+CIFSR
It will return an IP Address.
7. Now enable the multiplex mode by using AT+CIPMUX=1 (1 for multiple connection and 0 for single connection)
8. Now configure ESP8266 as server by using AT+CIPSERVER=1,port_no (port may be 80). Now your Wi-Fi is ready.
Here ‘1’ is used to create the server and ‘0’ to delete the server.
9. Now by using given command user can send data to local created server:
AT+CIPSEND =id, length of data
Id = ID no. of transmit connection
Length = Max length of data is 2 kb
10. After sending ID and Length to the server, we need to send data like : Serial.println(“circuitdigest@gmail.com”);
11. After sending data we need close the connection by given command:
AT+CIPCLOSE=0
Now data has been transmitted to local server.
12. Now type IP Address in Address Bar in web browser and hit enter. Now user can see transmitted data on webpage.