You are on page 1of 255

Functions

pinMode(pin, Mode)
• Configures the specified pin to behave either input or output.
• Parameters:
pin: the number of the pin whose mode you wish to set.
Mode: either INPUT or OUTPUT
Example:
int ledPin = 13; // LED connected to digital pin 13
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
}
digitalWrite(pin, value)
• Sets a pin configured as OUTPUT to either a
HIGH or a LOW state at the specified pin.
• The digitalWrite() function is also used to set
pullup resistors when a pin is configured as an
INPUT.
digitalRead(pin)
• Reads the value from a specified pin, it will be either
HIGH or LOW.
Example:
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the
voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the
voltage LOW
delay(1000); // wait for a second
}
Push Button
The pushbutton is a component that connects two points in a circuit
when you press it.
When the pushbutton is open (unpressed) there is no connection
between the two legs of the pushbutton, so the pin is connected to 5
volts (through the pull-up resistor) and we read a HIGH. When the
button is closed (pressed), it makes a connection between its two legs,
connecting the pin to ground, so that we read a LOW. (The pin is still
connected to 5 volts, but the resistor in-between them means that the
pin is "closer" to ground.)
Example
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
Example
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed. If it is, the buttonState is LOW:


if (buttonState == LOW) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
Knight Rider
Named this example in memory to a TV-series
from the 80's where the famous David Hasselhoff
had an AI machine driving his Pontiac. The car had
been augmented with plenty of LEDs in all
possible sizes performing flashy effects.
Example
Example
Example
int timer = 100;
void setup() {
// use a for loop to initialize each pin as an output:
for (int thisPin = 2; thisPin < 8; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop() {
// loop from the lowest pin to the highest:
for (int thisPin = 2; thisPin < 8; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}

}
Example

// loop from the highest pin to the lowest:


for (int thisPin = 7; thisPin >= 2; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
Seatwork
• Kindly write down a code for a condition of:
• 4 leds are used as OUTPUT
• The first 2 LED blinks with a delay of 1000 then turns LOW.
• After the first 2 LED turns low,
• The last 2 LED blinks with a delay also of 1000 then turns LOW.
Interfacing Seven Segment to an Arduino
• Common Cathode

• Common Anode
Using for Loop
void setup() {
// define pin modes
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
}
void loop() {
// loop to turn leds od seven seg ON
for(int i=2;i<9;i++)
{
digitalWrite(i,HIGH);
delay(600);
} // loop to turn leds od seven seg OFF
for(int i=2;i<9;i++)
{
digitalWrite(i,LOW);
delay(600);
}
delay(1000);
}
void setup() {
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
digitalWrite(9, 0); // start with the "dot" off
}
void loop() {
// write '9'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '8'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 1);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '7'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(7, 0);
digitalWrite(8, 0);
delay(1000);
// write '6'
digitalWrite(2, 1);
digitalWrite(3, 0);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 1);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '5'
digitalWrite(2, 1);
digitalWrite(3, 0);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 0);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
digitalWrite(2, 1);
digitalWrite(3, 0);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 0);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '4'
digitalWrite(2, 0);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '3'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 0);
digitalWrite(7, 0);
digitalWrite(8, 1);
delay(1000);
// write '2'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 0);
digitalWrite(5, 1);
digitalWrite(6, 1);
digitalWrite(7, 0);
digitalWrite(8, 1);
delay(1000);
// write '1'
digitalWrite(2, 0);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(7, 0);
digitalWrite(8, 0);
delay(1000);
// write '0'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 1);
digitalWrite(7, 1);
digitalWrite(8, 0);
delay(4000);
}
Array (typeName variableName [size])
An array is a collection of variables that are accessed with an index
number. Arrays in the C programming language, on which Arduino is
based, can be complicated, but using simple arrays is relatively
straightforward.
Example:
int myInts[6];
int myPins[] = {2, 4, 8, 3, 6};
int mySensVals[6] = {2, 4, -8, 3, 2};
char message[6] = "hello";
int timer = 100; // The higher the number, the slower the timing.
int ledPins[] = {
2, 7, 4, 6, 5, 3
}; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the
array)

void setup() {
// the array elements are numbered from 0 to (pinCount - 1).
// use a for loop to initialize each pin as an output:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
// loop from the lowest pin to the highest:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
}
Using Switch Case
Modulo %
Remainder operation calculates the remainder when one integer is
divided by another. It is useful for keeping a variable within a particular
range (e.g. the size of an array). The % (percent) symbol is used to carry
out remainder operation.
Syntax:
remainder = dividend % divisor;
Parameters:
remainder : variable. Allowed data types: int, float, double
dividend : variable or constant. Allowed data types: int
divisor : non zero variable or constant. Allowed data types: int
Example:
• int x = 0;
• x = 7 % 5; // x now contains 2
• x = 9 % 5; // x now contains 4
• x = 5 % 5; // x now contains 0
• x = 4 % 5; // x now contains 4
• x = -4 % 5; // x now contains -4
• x = 4 % -5; // x now contains 4
Led Control using Modulo
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin1 = 3; // the number of the LED pin
const int ledPin2 = 4; // the number of the LED pin
const int ledPin3 = 5; // the number of the LED pin
const int ledPin4 = 6; // the number of the LED pin
const int ledPin5 = 7; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int buttonPressCount = 0;
int numberOfLED = 5;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
pinMode(ledPin5, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
if (buttonPressCount % numberOfLED == 0){
digitalWrite(ledPin1, HIGH);} // turn LED1 on:
else{
digitalWrite(ledPin1, LOW);}
if (buttonPressCount % numberOfLED == 1){
digitalWrite(ledPin2, HIGH); }// turn LED2 on:
else{
digitalWrite(ledPin2, LOW)};
buttonPressCount++;
delay(300);
}
}
Modulo on 8-bit LED
void setup()
{
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
}
void loop()
{
for(byte i=0;i<255;i++)
{

byte a=i%2;
byte b=i/2 %2;
byte c=i/4 %2;
byte d=i/8 %2;
byte e=i/16 %2;
byte f=i/32 %2;
byte g=i/64 %2;
byte h=i/128 %2;
digitalWrite(2,a);
digitalWrite(3,b);
digitalWrite(4,c);
digitalWrite(5,d);
digitalWrite(6,e);
digitalWrite(7,f);
digitalWrite(8,g);
digitalWrite(9,h);

delay(200);
}
}
Array + Modulo 8bit LED Counter
int ledPins[] = {2,3,4,5,6,7,8,9}; //An array to hold the pin each LED is
connected to Arduino.
void setup () {
for (int i = 0; i<8;i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop () {
for (int i = 0; i<256;i++) {
iloveEcE(i);
delay(100);
}
}
void iloveEcE(int num) {
for (int i = 0; i<8; i++) {
If(num%2){
digitalWrite(ledPins[i], HIGH);}
else{
digitalWrite(ledPins[i], LOW);}
num/=2;
}
}
Logical Operators
LOGICAL AND (&&)
Description
Logical AND results in true only if both operands are true.
Example Code
This operator can be used inside the condition of an if statement.
if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // if BOTH the
switches read HIGH
// statements
}
Logical NOT (!)
Description
Logical NOT results in a true if the operand is false and vice versa.
Example Code
This operator can be used inside the condition of an if statement.
if (!x) { // if x is not true
// statements
}
It can be used to invert the boolean value.
x = !y; // the inverted value of y is stored in x
LOGICAL OR (||)
Description
Logical OR results in a true if either of the two operands is true.
Example Code
This operator can be used inside the condition of an if statement.
if (x > 0 || y > 0) { // if either x or y is greater than zero
// statements
}
Not Equal (!=)
Description
Compares the variable on the left with the value or variable on the
right of the operator. Returns true when the two operands are not
equal.
Syntax
x != y; // is false if x is equal to y and it is true if x is not equal to y
Example Code (SSD)
int a = 2; //For displaying segment "a"
int b = 3; //For displaying segment "b"
int c = 4; //For displaying segment "c"
int d = 5; //For displaying segment "d"
int e = 6; //For displaying segment "e"
int f = 8; //For displaying segment "f"
int g = 9; //For displaying segment "g"
void setup() {
pinMode(a, OUTPUT); //A
pinMode(b, OUTPUT); //B
pinMode(c, OUTPUT); //C
pinMode(d, OUTPUT); //D
pinMode(e, OUTPUT); //E
pinMode(f, OUTPUT); //F
pinMode(g, OUTPUT); //G
}
void displayDigit(int digit)
{
//Conditions for displaying segment a
if(digit!=1 && digit != 4)
digitalWrite(a,HIGH);

//Conditions for displaying segment b


if(digit != 5 && digit != 6)
digitalWrite(b,HIGH);

//Conditions for displaying segment c


if(digit !=2)
digitalWrite(c,HIGH);
//Conditions for displaying segment d
if(digit != 1 && digit !=4 && digit !=7)
digitalWrite(d,HIGH);

//Conditions for displaying segment e


if(digit == 2 || digit ==6 || digit == 8 || digit==0)
digitalWrite(e,HIGH);

//Conditions for displaying segment f


if(digit != 1 && digit !=2 && digit!=3 && digit !=7)
digitalWrite(f,HIGH);
//Conditions for displaying segment g
if (digit!=0 && digit!=1 && digit !=7)
digitalWrite(g,HIGH);
}
void turnOff()
{
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
}
void loop() {
for(int i=0;i<10;i++)
{
displayDigit(i);
delay(1000);
turnOff();
}
}
bitRead
Description
Reads a bit of a number.
Syntax
bitRead (x, n);
Parameters
x: the number from which to read.
n: which bit to read, starting at 0 for the least-significant (rightmost)
bit.
SSD using bitRead()
void setup()
{
for (int i = 0; i <= 13; i++)
pinMode(i, OUTPUT); //Set all pins from 0 to 13 as OUTPUT
}
//The line below is the array containing all the binary numbers for the
digits on a SSD from 0 to 9
const int number[11] = {0b1000000, 0b1111001, 0b0100100,
0b0110000, 0b0011001, 0b0010010, 0b0000010, 0b1111000,
0b0000000, 0b0010000};
void loop()
{
for (int tens = 0; tens < 10; tens++)

{
display_tens(tens);
}
}
void display_tens(const int tens)
{
int pin1, a, ones;
for (pin1 = 0, a = 0; pin1 < 7; pin1++, a++)
{
digitalWrite(pin1, bitRead(number[tens], a));
}
for (ones = 0; ones < 10; ones++)
{
display_ones(ones);
delay(300);
}
}
void display_ones(const int x){
int pin2, b;
for (pin2 = 7, b = 0; pin2 <= 13; pin2++, b++)
{
digitalWrite(pin2, bitRead(number[x], b));
}
}
SSD using ARRAY
void Display_Segment(int);
int digit[10][7] = {{ 0,1,1,1,1,1,1}, // Digit "0"
{ 0,0,0,0,1,1,0}, // Digit "1"
{ 1,0,1,1,0,1,1}, // Digit "2"
{ 1,0,0,1,1,1,1}, // Digit "3"
{ 1,1,0,0,1,1,0}, // Digit "4"
{ 1,1,0,1,1,0,1}, // Digit "5"
{ 1,1,1,1,1,0,1}, // Digit "6"
{ 0,0,0,0,1,1,1}, // Digit "7"
{ 1,1,1,1,1,1,1}, // Digit "8"
{ 1,1,0,1,1,1,1 }}; // Digit "9"
void setup()
{
// Seven Segment Pins as Output
for(int a=0 ; a<=6; a++){
pinMode(a, OUTPUT);
}
}
void loop()
{
for (int value = 0; value<=9; value++)
{
delay(1000);
Display_Segment(value);
}
delay(2500);
}
void Display_Segment(int value)
{
for (int x=6,startPin =0; x >= 0; x--, startPin++) {
digitalWrite(startPin, digit[value][x]);
}
}
Increment & Decrement
const int a = 8; //For displaying segment "a"
const int b = 9; //For displaying segment "b"
const int c = 4; //For displaying segment "c"
const int d = 5; //For displaying segment "d"
const int e = 6; //For displaying segment "e"
const int f = 2; //For displaying segment "f"
const int g = 3; //For displaying segment "g"
bool bPress = false;
const int IncbuttonPin = 10;
const int DecbuttonPin = 11;
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button
presses
int IncbuttonState = 0; // current state of the button
int lastIncbuttonState = 0; // previous state of the button
int DecbuttonState = 0; // current state of the button
int lastDecbuttonState = 0; // previous state of the button
void setup() {
// put your setup code here, to run once:
pinMode(a, OUTPUT); //A
pinMode(b, OUTPUT); //B
pinMode(c, OUTPUT); //C
pinMode(d, OUTPUT); //D
pinMode(e, OUTPUT); //E
pinMode(f, OUTPUT); //F
pinMode(g, OUTPUT); //G
pinMode( IncbuttonPin , INPUT_PULLUP );
pinMode( DecbuttonPin , INPUT_PULLUP );
displayDigit(buttonPushCounter);
}
void loop() {
IncbuttonState = digitalRead(IncbuttonPin);
DecbuttonState = digitalRead(DecbuttonPin);
checkIncButtonPress();
checkDecButtonPress();
if( bPress ){
bPress = false;
turnOff();
displayDigit(buttonPushCounter);
}
void checkIncButtonPress()
{
// compare the IncbuttonState to its previous state
if (IncbuttonState != lastIncbuttonState) {
// if the state has changed, increment the counter
if (IncbuttonState == LOW) {
// if the current state is HIGH then the button went from off to on:
bPress = true;
buttonPushCounter++;
if( buttonPushCounter > 9){ buttonPushCounter =0 ;
} // Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state, for next time through the loop
lastIncbuttonState = IncbuttonState;
}
void checkDecButtonPress()
{
// compare the IncbuttonState to its previous state
if (DecbuttonState != lastDecbuttonState) {
// if the state has changed, increment the counter
if (DecbuttonState == LOW) {
// if the current state is HIGH then the button went from off to on:
bPress = true;
buttonPushCounter--;
if( buttonPushCounter < 0){ buttonPushCounter =9 ;
Serial.println("on");
}}
// save the current state as the last state, for next time through the loop
lastDecbuttonState = DecbuttonState;
}
void displayDigit(int digit)
{
//Conditions for displaying segment a
if(digit!=1 && digit != 4)
digitalWrite(a,HIGH);
//Conditions for displaying segment b
if(digit != 5 && digit != 6)
digitalWrite(b,HIGH);
//Conditions for displaying segment c
if(digit !=2)
digitalWrite(c,HIGH);
if(digit != 1 && digit !=4 && digit !=7)
digitalWrite(d,HIGH);
//Conditions for displaying segment e
if(digit == 2 || digit ==6 || digit == 8 || digit==0)
digitalWrite(e,HIGH);
//Conditions for displaying segment f
if(digit != 1 && digit !=2 && digit!=3 && digit !=7)
digitalWrite(f,HIGH);
if (digit!=0 && digit!=1 && digit !=7)
digitalWrite(g,HIGH);
}
void turnOff()
{
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
}
Mini-Quiz

•Button 1 (Display
10,20,30,40,50,60,70,80,90)
•Button 2(Display 00 to 99)
•Button 3 (Increment)
•Button 4 (Decrement)
Port Registers
Port registers allow for lower-level and faster manipulation of the i/o
pins of the microcontroller on an Arduino board. The chips used on the
Arduino board (the ATmega8 and ATmega168) have three ports:

• B (digital pin 8 to 13)


• C (analog input pins)
• D (digital pins 0 to 7)
Data Direction Register (DDR)

The DDR register, determines whether


the pin is an INPUT or OUTPUT. The PORT
register controls whether the pin is HIGH
or LOW, and the PIN register reads the
state of INPUT pins set to input with
pinMode().
DDR and PORT registers may be both written to, and read. PIN
registers correspond to the state of inputs and may only be
read.

PORTD maps to Arduino digital pins 0 to 7


• DDRD - The Port D Data Direction Register - read/write
• PORTD - The Port D Data Register - read/write
• PIND - The Port D Input Pins Register - read only
PORTB maps to Arduino digital pins 8 to 13 The two high
bits (6 & 7) map to the crystal pins and are not usable
• DDRB - The Port B Data Direction Register -
read/write
• PORTB - The Port B Data Register - read/write
• PINB - The Port B Input Pins Register - read only
PORTC maps to Arduino analog pins 0 to 5. Pins 6 & 7 are
only accessible on the Arduino Mini
• DDRC - The Port C Data Direction Register - read/write
• PORTC - The Port C Data Register - read/write
• PINC - The Port C Input Pins Register - read only
Examples:

DDRD = B11111110; // sets Arduino pins 1 to 7 as outputs, pin


0 as input
DDRD = DDRD | B11111100; // this is safer as it sets pins 2 to 7
as outputs // without changing the value of pins 0 & 1, which
are RX & TX
PORTD = B10101000; // sets digital pins 7,5,3 HIGH
Example:
void setup() {
DDRD = B11111111;
}

void loop()
{
for(int i = 0; i<10;i++)
{
ShowDigit(i);
delay(500);
}
}
void ShowDigit(int digit) {
if(digit == 0) PORTD = B00111111; // 0
if(digit == 1) PORTD = B00000110; // 1
if(digit == 2) PORTD = B01011011; // 2
if(digit == 3) PORTD = B01001111; // 3
if(digit == 4) PORTD = B01100110; // 4
if(digit == 5) PORTD = B01101101; // 5
if(digit == 6) PORTD = B01111101; // 6
if(digit == 7) PORTD = B00000111; // 7
if(digit == 8) PORTD = B01111111; // 8
if(digit == 9) PORTD = B01101111; // 9
}
Define
A useful C component that allows the
programmer to give a name to a constant value
before the program is compiled. Defined
constants in arduino don't take up any program
memory space on the chip. The compiler will
replace references to these constants with the
defined value at compile time.
Syntax
#define constantName value

Example
#define Karl 0
// The compiler will replace any mention of Karl with the value 0 at
compile time
Debounce
Pushbuttons often generate spurious open/close transitions when
pressed, due to mechanical and physical issues: these transitions may
be read as multiple presses in a very short time fooling the program.
This example demonstrates how to debounce an input, which means
checking twice in a short period of time to make sure the pushbutton is
definitely pressed. Without debouncing, pressing the button once may
cause unpredictable results. This sketch uses the millis() function to
keep track of the time passed since the button was pressed.
Example:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output
flickers
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
// set initial LED state
digitalWrite(ledPin, ledState);
}
void loop() {
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
// set the LED:
digitalWrite(ledPin, ledState);
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
}
Ultrasonic Sensor
Ultrasonic sensors measure distance by using ultrasonic
waves.
The sensor head emits an ultrasonic wave and receives
the wave reflected back from the target. Ultrasonic
Sensors measure the distance to the target by measuring
the time between the emission and reception.
HC-SR04 Ultrasonic Sensor
It emits an ultrasound at 40 000 Hz which travels through
the air and if there is an object or obstacle on its path It
will bounce back to the module. Considering the travel
time and the speed of the sound you can calculate the
distance.
HC-SR04 Specifications
• Working Voltage: DC 5V
• Working Current: 15mA
• Working Frequency: 40Hz
• Max Range: 4m
• Min Range: 2cm
• Measuring Angle: 15 degree
• Trigger Input Signal: 10µS TTL pulse
• Echo Output Signal Input TTL lever signal and the range in proportion
• Dimension 45 * 20 * 15mm
Pins
• The HC-SR04 Ultrasonic Module has 4 pins, Ground,
VCC, Trig and Echo. The Ground and the VCC pins of the
module needs to be connected to the Ground and the 5
volts pins on the Arduino Board respectively and the
trig and echo pins to any Digital I/O pin on the Arduino
Board.
Triggering
In order to generate the ultrasound you need to set the Trig on a
High State for 10 µs. 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. The
Echo pin will output the time in microseconds the sound wave traveled.
For example, if the object is 10 cm away from the sensor, and the
speed of the sound is 340 m/s or 0.034 cm/µs the sound wave will
need to travel about 294 u seconds. But what you will get from the
Echo pin will be double that number because the sound wave needs to
travel forward and bounce backward. So in order to get the distance in
cm we need to multiply the received travel time value from the echo
pin by 0.034 and divide it by 2.
Pulsein()
• Reads a pulse (either HIGH or LOW) on a pin. For example,
if value is HIGH, pulseIn() waits for the pin to go
from LOWto HIGH, starts timing, then waits for the pin to
go LOW and stops timing. Returns the length of the pulse in
microseconds or gives up and returns 0 if no complete pulse was
received within the timeout.
• The timing of this function has been determined empirically and
will probably show errors in longer pulses. Works on pulses from
10 microseconds to 3 minutes in length.
Syntax
pulseIn(pin, value)
pulseIn(pin, value, timeout)

Parameters
pin: the number of the Arduino pin on which you want to read the pulse.
Allowed data types: int.
value: type of pulse to read: either HIGH or LOW. Allowed data types: int.
timeout (optional): the number of microseconds to wait for the pulse to
start; default is one second. Allowed data types: unsigned long.
Example:
int pin = 7;
unsigned long duration;

void setup() {
Serial.begin(9600);
pinMode(pin, INPUT);
}

void loop() {
duration = pulseIn(pin, HIGH);
Serial.println(duration);
}
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
}
Seatwork:
Design the following:
When the sensor detects an object distance is equals or below 100 cm, the
first LED turn on.
When the sensor detects an object distance is equals or below 150 cm, but
not lower than 100, the first LED turn off and the second LED turn on.
When the sensor detects an object distance is equals or below 200 cm, but
not lower than 150 the first and second LED turn off and the third LED will
turn on.
When the sensor is not detecting something, the fourth LED will turn on.
analogRead(pin)
Reads the value from the specified analog pin. The Arduino
board contains a 6 channel (8 channels on the Mini and
Nano), 10-bit analog to digital converter.
Parameters:
The number of the analog input pin to read from (0 to 5 on
most boards, 0 to 7 on the Mini and Nano)
Return:
An integer value in the range of 0 to 1023.
Example:
int analogPin = 3; // potentiometer wiper (middle terminal) connected to
analog pin 3
// outside leads to ground and +5V
int val = 0;
// variable to store the value read
void setup() {
}
void loop() {
val = analogRead(analogPin); // read the input
}
analogWrite(pin, value)
Writes an analog value to a pin.
Parameters:
pin: the pin to write to.
value: the duty cycle: between 0 (always off) and 255 (always on).
Returns:
nothing
Example:
int ledPin = 9; // LED connected to digital pin 9
int analogPin = 3; // potentiometer connected to analog pin 3
int val = 0; // variable to store the read value
void setup() {
pinMode(ledPin, OUTPUT); // sets the pin as output }
void loop() {
val = analogRead(analogPin); // read the input pin
analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023,
analogWrite values from 0 to 255
}
Pin Mapping
The analog pins can be used identically to the digital pins, using the
aliases A0 (for analog input 0), A1, etc.
Example:
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH);
Note:
The analogRead command will not work correctly if a pin has been
previously set to an output, so if this is the case, set it back to an input
before using analogRead.
tone()
Generates a square wave of the specified frequency (and 50% duty
cycle) on a pin. A duration can be specified, otherwise the wave
continues until a call to noTone(). The pin can be connected to a piezo
buzzer or other speaker to play tones.
Syntax:
tone(pin, frequency)
Tone(pin, frequency, duration)
Parameters:
Pin- the pin on which to generate the tone.
Frequency – the frequency of the tone in hertz (unsigned int)
Duration- the duration of the tone in milliseconds (unsigned long)
Returns:
Nothing
Notes:
If you want to play different pitches on multiple pins, you need to call
noTone() on one pin before calling tone() on the next pin.
Example:
int buzzerPin = 9;
int buttonPin = 7;
int ledPin = 6;
const int toneFreq = 523;

void setup()
{
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop()
{
int buttonState = digitalRead(buttonPin);
if (buttonState==LOW)
{
digitalWrite(ledPin, HIGH);
tone(buzzerPin, toneFreq);
}
else
{
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
}
}
Seatwork
Kindly write down a program in which you have a potentiometer and a
buzzer.
Scenario:
The potentiometer has a value range from (0 to 1023) and when it
reaches below 300 and above 900 the buzzer starts to produce a sound
with a frequency of 1khz, it will continue to produce sound until the
condition is true.
Serial
Used for communication between the Arduino board and a computer
or other devices. All Arduino boards have at least one serial port (also
known as a UART or USART): Serial. It communicates on digital pins 0
(RX) and 1 (TX) as well as with the computer via USB. Thus, if you use
these functions, you cannot also use pins 0 and 1 for digital input or
output.
Serial.begin()
Sets the data rate in bits per second (baud) for serial
data transmission. For communicating with the
computer, use one of these rates: 300, 600, 1200, 2400,
4800, 9600, 14400, 19200, 28800, 38400, 57600, or
115200.
Example:
For Arduino Uno:
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
}
For Arduino Mega:
void setup(){
Serial.begin(9600);
Serial1.begin(38400);
Serial2.begin(19200);
Serial3.begin(4800);
}
void loop() {
}
Serial.end()

Disables serial communication, allowing


the RX and TX pins to be used for general
input and output.
Serial.read()
Reads incoming serial data.
Example:
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) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
Serial.print()
Prints data to the serial port as human-readable ASCII text. This
command can take many forms. Numbers are printed using an ASCII
character for each digit.
Syntax:
Serial.print(val)
Serial.print(val, format)
Format
An optional second parameter specifies the base (format) to use; permitted values
are BIN(binary, or base 2), OCT(octal, or base 8), DEC(decimal, or base 10),
HEX(hexadecimal, or base 16). For floating point numbers, this parameter specifies
the number of decimal places to use.
Example:
Serial.print(78, BIN) gives "1001110“
Serial.print(78, OCT) gives "116“
Serial.print(78, DEC) gives "78“
Serial.print(78, HEX) gives "4E“
Serial.print(1.23456, 0) gives "1"
Serial.print(1.23456, 2) gives "1.23"
Serial.print(1.23456, 4) gives "1.2346"
Serial.println()
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').
Serial.write()
Writes binary data to the serial port. This
data is sent as a byte or series of bytes;
to send the characters representing the
digits of a number use the print()
function instead.
Serial.available()
Get the number of bytes (characters) available for
reading from the serial port. This is data that’s
already arrived and stored in the serial receive
buffer (which holds 64 bytes).
Example of analogRead()
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

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


void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
}
Light Dependent Resistor
An LDR is a component that has a (variable) resistance that changes
with the light intensity that falls upon it. This allows them to be used in
light sensing circuits.
Using an input in a voltage divider
• Most input transducers (sensors, suppose LDR) vary
their resistance and usually a Voltage divider is used to convert this to
a varying Voltage which is more useful. The Voltage signal can be fed
to other parts of the circuit, such as the input to an IC or a transistor
switch.
• The sensor is one of the resistances in the Voltage divider. It can be at
the top (R1) or at the bottom (R2), the choice is determined by when
you want a large value for the output Voltage Vo:
Choosing a resistor value
The value of the resistor R will determine the range of the output
Voltage Vo. For best results you need a large ‘swing’ (range) for Vo and
this is achieved if the resistor is much larger than the sensor’s minimum
resistance Rmin, but much smaller than the sensor’s maximum
resistance Rmax.

Then choose resistor value: R = square root of (Rmin × Rmax)


Choose a standard value which is close to this calculated value.
For example:
An LDR: Rmin = 100R, Rmax = 1M, so R = square root of (100 × 1M)
= 10K.
If the LDR is at the top (near +Vs),
Vo will be low in the dark and high in bright light.

If the LDR is at the bottom (near 0V),


Vo will be high in the dark and low in bright light.
Example code:
const int ledPin = 13;
const int ldrPin = A0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
}
void loop() {
int ldrStatus = analogRead(ldrPin);
if (ldrStatus <= 200) {
digitalWrite(ledPin, HIGH);
Serial.print("Its DARK, Turn on the LED : ");
Serial.println(ldrStatus);}
else {
digitalWrite(ledPin, LOW);
Serial.print("Its BRIGHT, Turn off the LED : ");
Serial.println(ldrStatus);
}
}
Time
delay()

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

Syntax
delay(ms)
delayMicroseconds()
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.

Syntax
delayMicroseconds(us)
micros()
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.

Syntax
Time = micros();
unsigned long time;
void setup(){
Serial.begin(9600);
} void loop()
{
Serial.print("Time: ");
time = micros();
Serial.println(time); //prints time since program started
delay(1000); // wait a second so as not to send massive amounts of
data
}
millis()
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.

Syntax
Time = millis();
constrain()
Constrains a number to be within a range.
Syntax
constrain(x,a,b)
Parameters
X, the number to constrain
a, lower end of the range
b, upper end of the range
sensVal = constrain(sensVal, 10, 150); // limits range of sensor values to
between 10 and 150
map()
Re-maps a number from one range to another. That is, a value
of fromLow would get mapped to toLow, a value
of fromHigh to toHigh, values in-between to values in-between, etc.
value: the number to map
fromLow: the lower bound of the value's current range
fromHigh: the upper bound of the value's current range
toLow: the lower bound of the value's target range
toHigh: the upper bound of the value's target range
Example
void setup() {
}
void loop() {
int val = analogRead(0);
val = map(val, 0, 1023, 0, 255);
analogWrite(9, val);
}
Seatwork
Given: Potentiometer Arduino UNO Buzzer
Light Dependent Resistor LED
Problem: The potentiometer will only vary from 0 to 255. When
the pot is equals or below 50, the buzzer will enable with a frequency
which is equals to the value of the potentiometer, and the LED is turn
ON. Display the ffg. “BOTH LED and BUZZER is ON”. When the pot
varies from 51 to 149 the buzzer will enable with a frequency of 1 khz
and the LED will blink continuously. Display potentiometer value. When
both conditions were false, the buzzer will enable with a frequency of
2khz, LED will turn OFF and display the ffg: “ERROR, CONDITIONS WERE
NOT MET”.
Arduino Serial Plotter
This tools gives you the ability to visualize your data in a plot that is
updated in real time.
ReadAnalogVoltage
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

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


void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
AnalogInOutSerial
int analogInPin = A0; // Analog input pin that the potentiometer is
attached
int analogOutPin = 9; // Analog output pin that the LED is attached to
int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0,
255);
// change the analog out value:
analogWrite(analogOutPin, outputValue);
// print the results to the Serial Monitor:
Serial.print("sensor = ");
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);

// wait 2 milliseconds before the next loop for the analog-to-digital


// converter to settle after the last reading:
delay(2);
}
Seatwork
Design a program with the following conditions:
Given:
LDR, buzzer , LED
When the value of the LDR is below 50 it will buzz with a frequency of
500 and will turn on the LED.
When the value of the LDR is higher than 50 but lesser than 100 the
buzzer will buzz with a frequency of 1000 and will turn off the LED.
If conditions were not satisfied both LED and buzzer are turned OFF.
Libraries

Libraries are files written in C or C++ (.c,


.cpp) which provide your sketches with
extra functionality (e.g. the ability to
control an LED matrix, or read an
encoder, etc.). They were introduced in
Arduino 0004.
To use an existing library in a sketch simply go to
the Sketch menu, choose "Import Library", and
pick from the libraries available. This will insert
an #include statement at the top of the sketch for
each header (.h) file in the library's folder. These
statements make the public functions and
constants defined by the library available to your
sketch. They also signal the Arduino environment
to link that library's code with your sketch when it
is compiled or uploaded.
Official Libraries
These are the "official" libraries that are included in the Arduino
distribution.
EEPROM - reading and writing to "permanent" storage
SoftwareSerial - for serial communication on any digital pins
Stepper - for controlling stepper motors
Wire - Two Wire Interface (TWI/I2C) for sending and receiving data
over a net of devices or sensors.
Contributed Libraries
Libraries written by members of the Arduino community.
LCD 4 Bit - control LCDs (using 4 data lines) LedControl - for controlling
LED matrices or seven-segment displays with a MAX7221 or MAX7219.
LedControl - an alternative to the Matrix library for driving multiple
LEDs with Maxim chips.
TextString - handle strings
Metro - help you time actions at regular intervals MsTimer2 - uses the
timer 2 interrupt to trigger an action every N milliseconds.
PS2Keyboard - read characters from a PS2 keyboard.
Servo - provides software support for Servo motors on any pins.
Servo Motor

The servo motor is usually a simple


DC Motor controlled for specific
angular rotation with the help of
additional servomechanism.
This library allows an Arduino board to
control RC (hobby) servo motors. Servos
have integrated gears and a shaft that can
be precisely controlled. Standard servos
allow the shaft to be positioned at various
angles, usually between 0 and 180 degrees.
Continuous rotation servos allow the
rotation of the shaft to be set to various
speeds.
Circuit
Servo motors have three wires: power, ground, and signal. The power
wire is typically red, and should be connected to the 5V pin on the
Arduino or Genuino board. The ground wire is typically black or brown
and should be connected to a ground pin on the board.
attach()
Attach the Servo variable to a pin. Note that in Arduino and earlier, the Servo
library supports only servos on only two pins: 9 and 10.
Syntax:
servo.attach(pin)
servo.attach(pin, min, max)
Parameters:
• servo: a variable of type Servo
• pin: the number of the pin that the servo is attached to
• min (optional): the pulse width, in microseconds, corresponding to the
minimum (0-degree) angle on the servo (defaults to 544)
• max (optional): the pulse width, in microseconds, corresponding to the
maximum (180-degree) angle on the servo (defaults to 2400)
Example:
#include <Servo.h>
Servo myservo;
void setup () {
myservo.attach(9);
}
void loop () {}
attached()
Check whether the Servo variable is attached to a pin.

Syntax:
servo.attached()

Returns
true if the servo is attached to pin; false otherwise.
detach()
Detach the Servo variable from its pin. If all Servo variables are
detached, then pins 9 and 10 can be used for PWM output with
analogWrite().

Syntax
servo.detach()
write()
Writes a value to the servo, controlling the shaft accordingly. On a
standard servo, this will set the angle of the shaft (in degrees), moving
the shaft to that orientation. On a continuous rotation servo, this will
set the speed of the servo (with 0 being full-speed in one direction, 180
being full speed in the other, and a value near 90 being no movement).
Syntax
servo.write(angle)
Parameters
angle: the value to write to the servo, from 0 to 180
Example:
#include <Servo.h>
Servo myservo;
void setup () {
myservo.attach(9);
myservo.write(90); //set servo to mid point
}
void loop () {
}
read()
Read the current angle of the servo (the value passed to the last call to
write()).

Syntax
servo.read()
Example Code:
include <Servo.h>

// Declare the Servo pin


int servoPin = 9;
// Create a servo object
Servo Servo1;

void setup() {
// We need to attach the servo to the used pin number
Servo1.attach(servoPin);
}
void loop(){
// Make servo go to 0 degrees
Servo1.write(0);
delay(1000);
// Make servo go to 90 degrees
Servo1.write(90);
delay(1000);
// Make servo go to 180 degrees
Servo1.write(180);
delay(1000);
}
Knob
Control the position of a RC (hobby) servo motor with your Arduino
and a potentiometer.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
val = analogRead(potpin); // reads the value of the potentiometer (value
between 0 and 1023)
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between
0 and 180)
myservo.write(val); // sets the servo position according to the scaled
value
delay(15); // waits for the servo to get there
}
Sweep
Sweeps the shaft of a RC servo motor back and forth across 180
degrees.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; 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
}
}
Mini-QUIZ
Given a potentiometer, buzzer, servo motor and LED.
Map the range of the potentiometer from 0 to 180. Display the
following data thru the serial monitor, use serial.println.
If the potentiometer varies from 0 to 90, the LED is ON and will control
the arm of the servo motor, buzzer will buzz if the pot hits 45 and 90
degrees with a frequency of 1 kHz, else noTone.
If the potentiometer varies from 91 to 180, the LED is OFF and will
control the arm of the servo motor, buzzer will buzz if the po hits 180
degress with a frequency of 500, else noTone.
Infrared Sensor
• Infrared waves are not visible to the human eye. In the
electromagnetic spectrum, infrared radiation can be found between
the visible and microwave regions. The infrared waves typically have
wavelengths between 0.75 and 1000µm.

• An Infrared Sensor is an electronic device, that emits in order to sense


some aspects of the surroundings. An IR sensor can measure the heat
of an object as well as detects the motion.
Passive Infrared
Passive IR (PIR) sensors use a pair of pyroelectric sensors to detect heat
energy in the surrounding environment. These two sensors sit beside
each other, and when the signal differential between the two sensors
changes (if a person enters the room, for example), the sensor will
engage. That may mean it triggers an alarm, notifies authorities, or
maybe turns on a floodlight. IR radiation focuses on each of the two
pyroelectric sensors using a series of lenses constructed as the sensor’s
housing. These lenses widen the device’s sensing area.
Pin Configuration
PIR sensor consists of three pins, ground, signal, and power at the side
or bottom. Generally, the PIR sensor power is up to 5V. It is very simple
and easy to interface the sensor with a microcontroller. The output of
the PIR is (usually digital output) either low or high.
PIR Sensor Circuit
The PIR sensor circuit consists of three pins, power supply pin, output
signal pin, and ground pin. The PIR sensor circuit is having ceramic
substrate and filter window as shown in the figure and also having
dome like structure called as Fresnel Lens.

Fresnel lens, succession of concentric rings, each consisting of an


element of a simple lens, assembled in proper relationship on a flat
surface to provide a short focal length. The Fresnel lens is used
particularly in lighthouses and to concentrate the light into a relatively
narrow beam.
Whenever, human being (even a
warm body or object with some
temperature) passes through
the field of view of PIR sensor,
then it detects the infrared
radiation emitted by a hot body
motion. Thus, the infrared
radiation detected by the sensor
generates an electrical signal
that can be used to activate an
alert system or buzzer or alarm
sound.
HC-SR501 PIR Sensor
Pin Number Pin Name Description

1 Vcc Input voltage is +5V for typical applications. Can range from
4.5V- 12V

2 High/Low Digital pulse high (3.3V) when triggered (motion detected)


Ouput (Dout) digital low(0V) when idle(no motion detected

3 Ground Connected to ground of circuit


Features:
• Wide range on input voltage varying from 4.V to 12V (+5V
recommended)
• Output voltage is High/Low
• Can distinguish between object movement and human movement
• Has to operating modes - Repeatable(H) and Non- Repeatable(H)
• Cover distance of about 120° and 7 meters
• Low power consumption of 65mA
• Operating temperature from -20° to +80° Celsius
Example:
int pirSensor = 4;
int LED = 10;

void setup () {
Serial.begin(9600);
pinMode(LED, OUTPUT);
pinMode(pirSensor, INPUT);

}
void loop () {
int pirSensorvalue = digitalRead(pirSensor);
if (pirSensorvalue == HIGH){
digitalWrite(LED, HIGH);
Serial.println(“THE LED IS ON”);
}
else{
digitalWrite(LED,LOW);
Serial.println(“THE LED IS OFF”);
}
}
Example:
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
if (pirState == HIGH){
// we have just turned of
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
}
Active Infrared
Active Infrared sensors transmit and measure the
reflection levels of infrared light. They can detect motion
and static presence, and have a high immunity to the
negative effects of external influences such as
reflections, sunlight and artificial light.
Pin Configuration
Example:
void setup() {
pinMode(7,INPUT);
Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop() {
Serial.print("IRSensorip ");
Serial.println(digitalRead(7));
if(digitalRead(7)==0)
{
digitalWrite(13,HIGH);
}
else{
digitalWrite(13,LOW);
}
}
Difference between IR and PIR
While PIR sensors are excellent if you want to detect
general movement, they don’t give you any more
information on your subject. To know more, you’ll need
an active IR sensor. Setting up an active IR sensor
requires both an emitter and receiver, but this sensing
method is simpler than its passive counterpart.
Sumobot Code:
#include Ultrasonic.h
Ultrasonic ultrasonic(4,3);
const int IN1=5;
const int IN2=6;
const int IN3=9;
const int IN4=10;
#define IR_sensor_front A0 // front sensor
#define IR_sensor_back A1 // rear senson
int distance ;
void setup()
{
Serial.begin(9600);
delay (5000);
}
void loop(){
int IR_front = analogRead(IR_sensor_front);
int IR_back = analogRead(IR_sensor_back);
distance = ultrasonic.read();
ROTATE(200); // start rotate
if (distance < 20){
Stop();
while (distance < 20 ) {
FORWARD(255);
distance = ultrasonic.read();
IR_front = analogRead(IR_sensor_front);
IR_back = analogRead(IR_sensor_back);
if ( IR_front > 650 || IR_back > 650 ) { break;}
delay(10); }
if (IR_front < 650 ) // < 650 means white line
{
Stop();
delay (50);
BACKWARD(255);
delay (500);
}

if (IR_back < 650 ) //


{
Stop();
delay (50);
FORWARD(255);
delay (500);
}
void FORWARD (int Speed){
//When we want to let Motor To move forward,
// just void this part on the loop section .
analogWrite(IN1,Speed);
analogWrite(IN2,0);
analogWrite(IN3,0);
analogWrite(IN4,Speed);
}
void BACKWARD (int Speed){
//When we want to let Motor To move forward,
// just void this part on the loop section .
analogWrite(IN1,0);
analogWrite(IN2,Speed);
analogWrite(IN3,Speed);
analogWrite(IN4,0);
}
void ROTATE (int Speed){
//When we want to let Motor To Rotate ,
// just void this part on the loop section .
analogWrite(IN1,Speed);
analogWrite(IN2,0);
analogWrite(IN3,Speed);
analogWrite(IN4,0);
}
void Stop(){
//When we want to Motor To stop ,
// just void this part on the loop section .
analogWrite(IN1,0);
analogWrite(IN2,0);
analogWrite(IN3,0);
analogWrite(IN4,0);
}
LCD (Liquid Crystal Display)
LCD (liquid crystal display) is the technology used for
displays in notebook and other smaller computers. Like
light-emitting diode (LED) and gas-plasma technologies,
LCDs allow displays to be much thinner than cathode
ray tube (CRT) technology. LCDs consume much less
power than LED and gas-display displays because they
work on the principle of blocking light rather than
emitting it.
LCD pins
The LCDs have a parallel interface, meaning that the microcontroller
has to manipulate several interface pins at once to control the display.
The interface consists of the following pins:
• A register select (RS) pin that controls where in the LCD's memory
you're writing data to. You can select either the data register, which
holds what goes on the screen, or an instruction register, which is
where the LCD's controller looks for instructions on what to do next.

• A Read/Write (R/W) pin that selects reading mode or writing mode


• An Enable pin that enables writing to the registers

• 8 data pins (D0 -D7). The states of these pins (high or low) are the bits
that you're writing to a register when you write, or the values you're
reading when you read.

• There's also a display constrast pin (Vo), power supply pins (+5V and
Gnd) and LED Backlight (Bklt+ and BKlt-) pins that you can use to
power the LCD, control the display contrast, and turn on and off the
LED backlight, respectively.
LiquidCrystal()

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
• 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()
Initializes the interface to the LCD screen, and specifies the dimensions
(width and height) of the display. Needs to be called before any other
LCD library commands.

Syntax
lcd.begin(cols, rows)
print()
Prints text to the LCD.
Syntax
lcd.print(data)
lcd.print(data, BASE)

data: the data to print (char, byte, int, long, or string)


BASE (optional): the base in which to print numbers: BIN for binary
(base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for
hexadecimal (base 16).
Example:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup()
{
lcd.print("hello, world!");
}

void loop() {}
setCursor()
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)
blink() and noBlink()
1. Display the blinking LCD cursor. If used in combination with
the cursor() function, the result will depend on the particular
display.
Syntax
lcd.blink()
2. Turns off the blinking LCD cursor.
Syntax
lcd.noBlink()
I2C (Inter-Integrated Circuit)
The Inter-integrated Circuit (I2C) Protocol is a protocol
intended to allow multiple “slave” digital integrated
circuits (“chips”) to communicate with one or more
“master” chips. Like the Serial Peripheral Interface
(SPI), it is only intended for short distance
communications within a single device. Like
Asynchronous Serial Interfaces (such as RS-232 or
UARTs), it only requires two signal wires to exchange
information.
Short History
The I2C bus was designed by Philips in the early ’80s to allow easy
communication between components which reside on the same circuit
board. Philips Semiconductors migrated to NXP in 2006.

The name I2C translates into “Inter IC”. Sometimes the bus is called IIC or I²C
bus.

The I2C protocol is used to establish communication between two or more


ICs (Integrated Circuits), hence why it’s known as Inter-Integrated Circuit
(I2C) communication. However, it should be noted that I2C could also be
used as a communication protocol between two ICs that are located on the
same PCB.
Where and how it is used?
In short, when you need to establish short distance communication
within the same board or device, you can use I2C. It requires only two
bidirectional wires for transmitting and receiving information. You also
need to know that I2C protocol supports serial communication only.
The protocol is very popular and multiple peripheral ICs are connected
in master-slave configurations. Talking about master-slave
configuration, you have a lot of flexibility when it comes to using the
I2C protocol. I2C allows designers to establish two-way communication
between multiple master ICs and slave ICs. In fact, you can connect as
many as 1008 slave devices.
SDA and SDL
This is just two wires, called SCL and SDA. SCL is
the clock line. It is used to synchronize all data
transfers over the I2C bus. SDA is the data line.
The SCL & SDA lines are connected to all devices
on the I2C bus. There needs to be a third wire
which is just the ground or 0 volts. There may also
be a 5volt wire is power is being distributed to the
devices.
I2C Module
At the left side of the module we have 4 pins, and two are voltage and
ground, and the other two are the I2c (SDA/ and SCL). The board has a
tripper pot to adjust the contrast of the LCD, and the jumper located at
the opposite side allows the back-light controlled by the program or
remain off.
Wire Library
This library allows you to communicate with I2C / TWI devices.
On the Arduino boards with the R3 layout (1.0 pinout), the
SDA (data line) and SCL (clock line) are on the pin headers
close to the AREF pin. The Arduino Due has two I2C / TWI
interfaces SDA1 and SCL1 are near to the AREF pin and the
additional one is on pins 20 and 21.
As a reference the table below shows where TWI pins are
located on various Arduino boards.
Board I2C / TWI pins
Uno, Ethernet A4 (SDA), A5 (SCL)
Mega2560 20 (SDA), 21 (SCL)
Leonardo 2 (SDA), 3 (SCL)
Due 20 (SDA), 21 (SCL), SDA1, SCL1
Example:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the


LCD I2C address, if it's not working try 0x27.
void setup(){
lcd.begin(16,2); // iInit the LCD for 16 chars 2 lines
lcd.backlight(); // Turn on the backligt (try lcd.noBaklight() to turn it
off)
lcd.setCursor(0,0); //First line
lcd.print(“IreallyLOVeEcE");
lcd.setCursor(0,1); //Second line
lcd.print(“Preboard is Life");
}

void loop(){
}
Example:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// set the LCD address to 0x27 for a 16 chars 2 line display


// A FEW use address 0x3F
// Set the pins on the I2C chip used for LCD connections:
// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the
LCD I2C address
void setup() {
Serial.begin(9600);
lcd.begin(16,2); // initialize the lcd for 16 chars 2 lines, turn on backlight

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


{
lcd.backlight();
delay(250);
lcd.noBacklight();
delay(250);
}
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Hello, world!");
delay(1000);
lcd.setCursor(0,1);
lcd.print("HI!Kumusta na?");
delay(8000);
lcd.clear();
lcd.setCursor(0,0); //Start at character 0 on line 0
lcd.print("Use Serial Mon");
lcd.setCursor(0,1);
lcd.print("Type to display");

}
void loop(){
// when characters arrive over the serial port...
if (Serial.available()) {
// wait a bit for the entire message to arrive
delay(100);
// clear the screen
lcd.clear();
// read all the available characters
while (Serial.available() > 0) {
// display each character to the LCD
lcd.write(Serial.read());
}
}
}
Addressing

A0 A1 A2 HEX Address
1 1 1 0x27
0 1 1 0x26
1 0 1 0x25
0 0 1 0x24
1 1 0 0x23
0 1 0 0x22
1 0 0 0x21
0 0 0 0x20
Keypad
A keypad is one of the most commonly used input devices in
microprocessor applications. In a standard keypad wired as an X-Y
switch matrix, normally-open switches connect a row to a column
when pressed. If a keypad has 12 keys, it is wired as 3 columns by 4
rows. A 16 key pad would have 4 columns by 4 rows.
Keypads are used in all types of devices, including cell phones, fax
machines, microwaves, ovens, door locks, etc. They’re practically
everywhere. Tons of electronic devices use them for user input.
Pin Connections
One of the most mysterious things
about these keypads is that they
usually come with no
documentation, so a user is left to
figure out the pin configuration for
him or herself. With the keypad
facing up so that the keys are up
and facing you, from left to right,
the 1st 4 pins are the row pins and
the last 4 pins are the column pins.
Functions
Keypad(makeKeymap(userKeymap), row[], col[], rows, cols)
const byte rows = 4; //four rows
const byte cols = 3; //three columns
char keys[rows][cols] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'#','0','*'}
};
byte rowPins[rows] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[cols] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );
Instantiates a Keypad object that uses pins 5, 4, 3, 2 as row pins, and 8,
7, 6 as column pins.
This keypad has 4 rows and 3 columns, resulting in 12 keys.
char waitForKey()

This function will wait forever until someone


presses a key. Warning: It blocks all other
code until a key is pressed. That means no
blinking LED's, no LCD screen updates, no
nothing with the exception of interrupt
routines.
char getKey()

Returns the key that is pressed, if any.


This function is non-blocking.
KeyState getState()

Returns the current state of any of


the keys.
The four states are IDLE, PRESSED,
RELEASED and HOLD.
boolean keyStateChanged()

Let's you know when the key has


changed from one state to another. For
example, instead of just testing for a valid
key you can test for when a key was
pressed.
setHoldTime(unsigned int time)

Set the amount of milliseconds the


user will have to hold a button until
the HOLD state is triggered.
setDebounceTime(unsigned int time)

Set the amount of milliseconds the


keypad will wait until it accepts a new
keypress/keyEvent. This is the "time
delay" debounce method.
addEventListener(keypadEvent)

Trigger an event if the keypad is used.


You can load an example in the Arduino
IDE.
Example:
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'#','0','*'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the
keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad
keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop(){
char key = keypad.getKey();

if (key != NO_KEY){
Serial.println(key);
}
}
#include <Keypad.h>

const byte ROWS = 4; // Four rows


const byte COLS = 3; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'#','0','*'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { 9, 8, 7, 6 };
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { 12, 11, 10 };

// Create the Keypad


Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

#define ledpin 13
void setup(){
pinMode(ledpin,OUTPUT);
digitalWrite(ledpin, HIGH);
Serial.begin(9600);
}
void loop() {
char key = kpd.getKey();
if(key) // Check for a valid key.
{
switch (key)
{
case '*':
digitalWrite(ledpin, LOW);
break;
case '#':
digitalWrite(ledpin, HIGH);
break;
default:
Serial.println(key);
}
}
}
Notes on using the library
• The library is non-blocking which means you can press and hold the
key all day long and your Arduino will continue processing the rest of
your code.
• Consider, though, when you are writing your code that every delay()
you use will take processing time away from the keypad. Something
as short as delay(250) can make the keypad seem very unresponsive.
And the same thing will happen if you sprinkle a bunch of delay(10)'s
all through your code.
• The function getKey() returns a key value as soon as you press the key
but it does not repeat automatically. Also, when you release the key
you can track the key RELEASED event if you are using the
eventListener feature of the library.

You might also like