0% found this document useful (0 votes)
21 views

Arduino Code S22

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Arduino Code S22

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Arduino

Page 1 of 55
Power USB
Arduino board is powered by using the USB cable.

Power (Barrel Jack)


Arduino boards can also be powered directly from the AC mains power supply by connecting
it to the Barrel Jack (2).

Voltage Regulator
The function of the voltage regulator is to control the voltage given to the Arduino board and
stabilize the DC voltages used by the processor and other elements.

Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. The number printed on top of
the Arduino crystal is 16.000. It means that the frequency is 16,000,000 Hertz or 16 MHz

Arduino Reset
There are two ways to reset the board (to start the program from the beginning). One is to use
the reset button (17) on the board. Other is to connect an external reset button to the Arduino
pin labelled RESET (5).

Pins (3.3, 5, GND, Vin)


 3.3V (6) − Supply 3.3 output volt
 5V (7) − Supply 5 output volt
 GND (8)(Ground) − There are several GND pins on the Arduino, any of which can be
used to ground your circuit.
 Vin (9) − This pin also can be used to power the Arduino board from an external power
source, like AC mains power supply.

Analog pins
The Arduino UNO board has six analog input pins A0 through A5. These pins can read the
signal from an analog sensor like the humidity sensor or temperature sensor and convert it into
a digital value that can be read by the microprocessor.

Page 2 of 55
Main microcontroller
Each Arduino board has its own microcontroller (11). It is the brain of the board. The main IC
(integrated circuit) on the Arduino is slightly different from board to board. The microcontrollers
are usually of the ATMEL Company.

ICSP pin (In Circuit Serial Programming)


ICSP (12) is an AVR, a tiny programming header for the Arduino. It is SPI (Serial Peripheral
Interface), the "expansion" of the output.

Power LED indicator


This will light up indicating that the board is powered up correctly.

TX and RX LEDs (Transmit and Receive)


These appear in two places on the Arduino UNO board. First, at the digital pins 0 and 1, to
indicate the pins responsible for serial communication. Second, the TX and RX led (14). The
TX led flashes with different speed while sending the serial data. The speed of flashing
depends on the baud rate used by the board. RX flashes during the receiving process.

Digital I/O
There are 14 digital I/O pins (15) (of which 6 provide PWM (Pulse Width Modulation) output
and labeled as “~”). These pins can be configured to work as input digital pins to read logic
values (0 or 1) or as digital output pins to drive different modules like LEDs, etc. (PWM pins
are 3, 5, 6, 9, 10, 11)

AREF
AREF stands for Analog Reference. It is used to set an external reference voltage (between 0
and 5 Volts) as the upper limit for the analog input pins.

Page 3 of 55
Arduino Program structure
Arduino programs can be divided in three main parts: Structure, Values (variables and
constants), and Functions.
Software structure consist of two main functions −
 Setup( ) function: The setup() function is called when a sketch starts. Use it to initialize
the variables, pin modes, start using libraries, etc. The setup function will only run once,
after each power up or reset of the Arduino board.
 Loop( ) function: After creating a setup() function, which initializes and sets the initial
values, the loop() function will do as per its name and loops consecutively, allowing the
program to change and respond. It is used to control the Arduino board.

Page 4 of 55
Data types of ‘C’ used in Arduino programming
 Void : The function is not returning something.
 Boolean: True/false
 char
 unsigned char
 byte
 int
 unsigned int
 word
 long
 unsigned long
 short
 float
 double
 long double
 array
 string - char array

Operators
 Arithmetic Operators (+, -, *, /, %)
 Comparison Operators (==, <=, >=, <, >, !=)
 Boolean Operators (&&, ||, !)
 Bitwise Operators (&, |, ^, ~, <<, >>)
 Compound Operators (++, --, +=, -=, *=, /=, %=, |=, &=)

Page 5 of 55
Working with single LED
void setup( )
{
pinMode(13,OUTPUT);
}
void loop( )
{
digitalWrite(13,HIGH);
delay(1000);
digitalWrite(13,LOW);
delay(1000);
}

Working with multiple LEDs

With 2 LEDs
void setup( )
{
pinMode(13,OUTPUT);
pinMode(12,OUTPUT);
}
void loop( )
{
digitalWrite(13,HIGH);
digitalWrite(12,LOW);
delay(1000);
digitalWrite(13,LOW);
digitalWrite(12,HIGH);
delay(1000);
}
Page 6 of 55
With 3 LEDs
void setup( )
{
pinMode(13,OUTPUT);
pinMode(12,OUTPUT);
pinMode(11,OUTPUT);
}
void loop( )
{
digitalWrite(13,HIGH);
digitalWrite(12,LOW);
digitalWrite(11,LOW);
delay(500);
digitalWrite(13,LOW);
digitalWrite(12,HIGH);
digitalWrite(11,LOW);
delay(500);
digitalWrite(13,LOW);
digitalWrite(12,LOW);
digitalWrite(11,HIGH);
delay(500);
}

Page 7 of 55
Program to ON the LED using Push button

const int buttonPin = 2; // the number of the pushbutton pin


const int ledPin = 13; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop()
{
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH)
digitalWrite(ledPin, HIGH);
else
digitalWrite(ledPin, LOW);
}

Page 8 of 55
Program to check the state of the button (1 if pressed, else 0)

(Note: In C/C++, // is used to give single line comment and /*……*/ is used to give multi line
comments)

// digital pin 2 has a pushbutton attached to it. Give it a name:


int pushButton = 2;

// the setup routine runs once when you press reset:


void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
}

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


void loop() {
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(2000); // delay in between reads for stability
}

Page 9 of 55
Program to turn on the LED and turn off the LED by pressing the push button
(State Change Detection)

// this constant won't change:


const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to

// Variables will change:


int buttonPushCounter = 0; // counter for the number of button
presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button

void setup()
{
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);

Page 10 of 55
}
void loop()
{
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state


if (buttonState != lastButtonState)
{
// if the state has changed, increment the counter
if (buttonState == HIGH)
{
// if the current state is HIGH then the button went from off to on:
buttonPushCounter++;
if (buttonPushCounter % 2 != 0)
{
digitalWrite(ledPin, HIGH);
Serial.println("LED is ON now");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}
else
{
digitalWrite(ledPin, LOW);
Serial.println("LED is OFF now");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}

Page 11 of 55
delay(1); // to let the led on or off for few milliseconds
}
}
// save the current state as the last state, for next time through the
loop
lastButtonState = buttonState;
}

Page 12 of 55
Program to Light multiple LEDs in sequence and then in reverse.

int ledPins[ ] = {13, 12, 11, 10, 9}; // an array of pin numbers to which LEDs are attached
int pinCount = 5; // the number of pins (i.e. the length of the array)
void setup()
{
int thisPin =0;
for ( ; thisPin < pinCount; thisPin++)
pinMode(ledPins[thisPin], OUTPUT);
}
void loop()
{
for (int thisPin = 0; thisPin < pinCount; thisPin++)
{
digitalWrite(ledPins[thisPin], HIGH);
delay(500);
digitalWrite(ledPins[thisPin], LOW);
}

for (int thisPin = pinCount - 2; thisPin >= 0; thisPin--)


{

Page 13 of 55
digitalWrite(ledPins[thisPin], HIGH);
delay(500);
digitalWrite(ledPins[thisPin], LOW);
}
}

Page 14 of 55
Program to take input from Serial Monitor and analyze that input that
whether it’s alphanumeric, ASCII character, numeric value, digit,
whitespace, etc.

void setup()
{
Serial.begin(9600);
while (!Serial) ; // wait for serial port to connect. Needed for native USB port only
Serial.println("Send any byte and get everything I can share about it");
Serial.println();
}

void loop()
{
if (Serial.available() > 0)
{
int thisChar = Serial.read();
Serial.print("You have sent : \'");
Serial.write(thisChar);
Serial.print("\' ASCII Value: ");
Serial.println(thisChar);

// analyze what was sent:


if (isAlphaNumeric(thisChar))
Serial.println("it's alphanumeric");
if (isAlpha(thisChar))
Serial.println("it's alphabetic");
if (isAscii(thisChar))

Page 15 of 55
Serial.println("it's ASCII");
if (isWhitespace(thisChar))
Serial.println("it's whitespace");
if (isControl(thisChar))
Serial.println("it's a control character");
if (isDigit(thisChar))
Serial.println("it's a numeric digit");
if (isGraph(thisChar))
Serial.println("it's a printable character that's not whitespace");
if (isLowerCase(thisChar))
Serial.println("it's lower case");
if (isPrintable(thisChar))
Serial.println("it's printable");
if (isPunct(thisChar))
Serial.println("it's punctuation");
if (isSpace(thisChar))
Serial.println("it's a space character");
if (isUpperCase(thisChar))
Serial.println("it's upper case");
if (isHexadecimalDigit(thisChar))
Serial.println("it's a valid hexadecimaldigit (i.e. 0 - 9, a - F, or A - F)");

Serial.println();
Serial.println("Give me another byte:");
Serial.println();
}
}

Page 16 of 55
Program to take String as input from Serial Monitor and convert it to
lowercase and uppercase

void setup()
{
Serial.begin(9600);
while (!Serial); // wait for serial port to connect. Needed for native USB port only");
Serial.println("\n\nEnter any String and it will be changed to Upper and Lower case:");
Serial.println();
}

void loop()
{
if (Serial.available() > 0)
{
String str = Serial.readString();
Serial.println("The entered string is :\t");
Serial.println(str);
str.toUpperCase();
Serial.println("Uppercase string is :\t");
Serial.println(str);
Serial.println();
Serial.println("Lowercase string is :\t");
str.toLowerCase();
Serial.println(str);
Serial.println();
while(true);
}
}

Page 17 of 55
String Comparison
 Checking the equality of two strings
o Using != operator : In this, the two strings should be exactly same by characters
and the case too.
o Using equals() function : This function works same as of the operator !=.
Syntax: str1.equals(str2)
o Using equalsIgnoreCase() function : This function will ignore the inequality of the
case.
Syntax: str1.equals(str2)
 Checking which string is greater or smaller
o Using >=, <=, >, < operator : In this, the two strings are compared for the
alphabetical sorting.
o Using compareTo() function : This function evaluates on the first character that's
different. It will subtract the ASCII code of the mismatched character of the
parametrized string from the invoked string.
If the difference is
>0, the invoked string is greater
<0, the parametrized string is greater
=0, both strings are equal

Page 18 of 55
Program to compare two strings
String stringOne, stringTwo;

void setup()
{
Serial.begin(9600);
while (!Serial);
Serial.println("\n\nComparing Strings:");
Serial.println();
}

void loop()
{
stringOne = "This";
stringTwo = "this";
if (stringOne != stringTwo)
Serial.println(stringOne + " != " + stringTwo);

if (stringOne.equals(stringTwo))
Serial.println(stringOne + " equals " + stringTwo);
else
Serial.println(stringOne + " does not equal " + stringTwo);

if (stringOne.equalsIgnoreCase(stringTwo))
Serial.println(stringOne + " equals (ignoring case) " + stringTwo);
else
Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo);

Page 19 of 55
stringOne = "1";
int numberOne = 1;
if (stringOne.toInt() == numberOne)
Serial.println(stringOne + " = " + numberOne);

stringOne = "2";
stringTwo = "1";
if (stringOne >= stringTwo)
Serial.println(stringOne + " >= " + stringTwo);

stringOne = String("Bubble");
if (stringOne < "Charming")
Serial.println(stringOne + " < Charming");

if (stringOne > "Arriving")


Serial.println(stringOne + " > Arriving");

if (stringOne <= "Bubble")


Serial.println(stringOne + " <= Bubble");

if (stringOne >= "Bubbl")


Serial.println(stringOne + " >= Bubbl");

stringOne = "IICS";

Page 20 of 55
stringTwo = "iics";
if (stringOne.compareTo(stringTwo) < 0)
Serial.println(stringOne + " comes before " + stringTwo);
else
Serial.println(stringOne + " comes after " + stringTwo);
while(true);
}

Page 21 of 55
Program to accept the string of acceptable length
String txtMsg = "";
unsigned int lastStringLength = txtMsg.length();
void setup()
{
Serial.begin(9600);
while (!Serial);
Serial.println("\n\nString length():");
Serial.println();
}

void loop()
{
if (Serial.available() > 0)
{
String txtMsg = Serial.readString();
if (txtMsg.length() != lastStringLength)
{
Serial.println(txtMsg);
Serial.println(txtMsg.length());
if (txtMsg.length() < 10)
Serial.println("That's a perfectly acceptable text message");
else
Serial.println("That's too long for a text message.");
lastStringLength = txtMsg.length();
}
}
}

Page 22 of 55
Program to trim the extra space from the input string (from both ends)
void setup()
{
Serial.begin(9600);
while (!Serial);
Serial.println("\n\nString length() and trim():");
Serial.println();
}

void loop()
{
if(Serial.available() > 0)
{
String str = Serial.readString();
Serial.print(str);
Serial.print("<--- end of string. Length: ");
Serial.println(str.length());

// trim the white space off the string:


str.trim();
Serial.print(str);
Serial.print("<--- end of trimmed string. Length: ");
Serial.println(str.length());

// do nothing while true:


while (true);
}
}

Page 23 of 55
Program to accept two strings as input by the user, print their length and
match whether they are equal or not. If not, then check which should come
before or after as per the sorting.
String str1, str2;
unsigned int len1, len2;
void setup()
{
Serial.begin(9600);
while(!Serial);
Serial.println("Enter two strings and check:\n");
}
void loop()
{
if(Serial.available()>0)
{
str1 = Serial.readString();
len1 = str1.length();
Serial.println("Length of string " + str1 + " is " + len1);
str2 = Serial.readString();
len2 = str2.length();
Serial.println("Length of string " + str2 + " is " + len2);
if(str1.equals(str2))
Serial.println("Both the strings are same");
else
if(str1.compareTo(str2)>0)
Serial.println(str1 + " comes after " + str2);
else
Serial.println(str1 + " comes before " + str2);
}}

Page 24 of 55
Program to take substring from the string input
void setup()
{
Serial.begin(9600);
while (!Serial);
Serial.println("\n\nString substring():");
Serial.println();
}

void loop()
{
String stringOne = "IICS Computer Education";
Serial.println(stringOne);
if (stringOne.substring(14) == "Education")
Serial.println("Substring matched to Education");
if (stringOne.substring(5, 9) == "Comp")
Serial.println("Substring matched with Comp");
while (true);
}

Page 25 of 55
Program to print the ASCII values of the characters in decimal, octal,
hexadecimal and binary number system
void setup()
{
Serial.begin(9600);
while (!Serial);
Serial.println("ASCII Table ~ Character Map");
}

int thisByte = 33;

void loop()
{
Serial.write(thisByte);
Serial.print(", dec: ");
Serial.print(thisByte);
Serial.print(", hex: ");
Serial.print(thisByte, HEX);
Serial.print(", oct: ");
Serial.print(thisByte, OCT);
Serial.print(", bin: ");
Serial.println(thisByte, BIN);
if (thisByte == 126)
while (true);
thisByte++;
}

Page 26 of 55
Arduino analogRead ( )
The analogRead( ) function reads the value from the specified analog pin present on the
particular Arduino board.
The ADC (Analog to Digital Converter) on the Arduino board is a multichannel
converter. It maps the input voltage and the operating voltage between the values 0 and
1023. The operating voltage can be 5V or 3.3V.
The values from 0 to 1023 are the integer values. It can also be written as 0 to (210) -1.
The time duration to read an analog input signal on the boards (UNO, Mega, Mini, and
Nano) is about 100 microseconds or 0.0001 seconds.
Hence, the maximum reading rate of analog input is about 10000 times per second.
The syntax is:
analogRead(pin)
where, pin is the name of the particular analog pin to read from.
The data type is int.

Page 27 of 55
Light Detective Resistor (LDR)
(Photoresistor)

int LDRvalue =0;


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

void loop()
{
LDRvalue = analogRead(A0);
Serial.println(LDRvalue);
delay(500);
}

Page 28 of 55
Program to turn on the LED when there is dark and automatically turn off
the light when there is light already

int led = 5;
int ldr = A0;
int threshold = 300;
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(ldr,INPUT);
}

void loop()
{

Page 29 of 55
int y = analogRead(ldr);
Serial.println(y);
if (y <=threshold)
digitalWrite(led,HIGH);
else
digitalWrite(led,LOW);
delay(200);
}

Page 30 of 55
Arduino Library
The Library is considered as the advanced feature, which extends the capabilities of the
Arduino IDE. It means that the libraries provide extra functionality to the programming
platform of Arduino.
The libraries in Arduino are written in C or C++ (.cpp). These libraries allow us to
manipulate data and work with the hardware.
To implement any Library in the Arduino IDE, go to the Sketch -> Import Library.
There are several libraries available for download. We can also create our own library.

Standard Libraries
The standard libraries are listed below:
EEPROM Library
It stands for Electronic Erasable Programmable Read Only Memory. The EEPROM is
associated with the microcontroller present on the AVR or Arduino Boards. The EEPROM
library allows us to read the bytes stored in the memory when the power of the board is
off.
The size of EEPROM varies in different boards, such as 1KB or 1024 bytes on the
ATmega328P. It can also be of 4KB or 4096 bytes on the Microcontroller ATmega2560,
etc.
The library is declared as:
#include <EEPROM.h>
For example, EEPROM Read, EEPROM Clear, EEPROM Write, EEPROM Get, EEPROM
Update, EEPROM Put, EEPROM Iteration, etc.

Ethernet Library
The Ethernet library works with the Arduino Ethernet shield and other related devices.
The Ethernet library allows us to connect the Arduino board to the Internet.
The SPI bus acts as an intermediate between the board and the shield.
The associated library is:

Page 31 of 55
#include <Ethernet.h>
#include <SPI.h>
For example, TelnetClient, WebServer, WebClientRepeating, WebClient, ChatServer,
DnsWebClient, UdpNtpClient, UdpSendReceiveString, etc.

Firmata Library
For the programming environment, we can create custom firmware without producing
our own objects and protocols.
It is used to implement the firmware protocol, which communicates with the software on
the host computer.
The associated library is:
#include <Firmata.h>

GSM Library (Global System Mobile communication)


The GSM library exists on the IDE version 1.0.4 and up.
The GSM library allows us to perform the operations on the Arduino board similar to the
GSM phone, such as internet connection, send and receive messages, and to place voice
calls.
The library is declared as:
#include <GSM.h>

Liquid Crystal Library


It is a library that permits Arduino to communicate with LCDs, which are based on a
compatible chipset called Hitachi HD44780. Such chipsets are found on most types of
text-based LCDs. It works with either an 8-bit mode or 4-bit mode. Here, the bit mode
signifies the data lines in addition to the enable, rs, and rw control lines (optional).
The library is declared as:
#include <LiquidCrystal.h>
The examples are Hello World, Cursor, Blink, etc.

Page 32 of 55
SD Library (Secure Digital Memory Card)
It allows writing to or reading from SD cards. For example, Arduino Ethernet Shield. The
file names include the paths separated by the forward slashes, which are passed to the
SD Library. But, SPI is used for the communication between the SD card and the Arduino.
The library is declared as:
#include <SPI.h>
#include <SD.h>
The examples are Dump files, List Files, Read Write, etc.

Servo Library
The Servo library permits Arduino to work with servo motors. It allows controlling the
integrated shaft and gears. We can also position shaft at different angles between 0 and
180 degrees. The servo library on Arduino boards can support upto 12 motors, while on
Arduino Mega board, it can support upto 48 motors.
The library is declared as:
#include <Servo.h>

SPI Library
The SPI (Serial Peripheral Interface) is a serial data protocol. The microcontrollers use
the serial protocol to communicate over short distances with one or more peripheral
devices quickly.
The required connection of SPI is a full-duplex that allows devices to simultaneously sent
and receive data.
The library is declared as:
#include <SPI.h>
The examples are Dump files, List Files, Read Write, etc.

Stepper Library
The Stepper library in Arduino permits to control of bipolar or unipolar stepper motors.
Page 33 of 55
The library is declared as:
#include <Stepper.h>
The Stepper includes stepper speed control, stepper one revolution, etc.

Software Serial Library


The Software Serial Library permits serial communication over digital Input/output pins.
The 0 and 1 pins are inbuilt on Arduino for the serial interface. We can include multiple
serial ports in our code that can operate with speed up to 115200 bps (bits per second).
The library is declared as:
#include <SoftwareSerial.h>

TFT LCD Library (Thin Film Transistor)


The TFT LCD library is included in the IDE version 1.0.5 and later. It allows the Arduino
to communicate with the TFT LCD screen. It further helps to draw images, shapes, lines,
and text to the screen.
The SD card slot present on the onboard screen can be used by implementing the SD
library.
The TFT library for communication depends on the SPI library with the SD card and
screen.
The library is declared as:
#include <SPI.h>
#include <TFT.h>

WiFi Library (Wireless Fidelity)


The WiFi library permits Arduino to establish a connection with the internet. It can either
be a server to receive the incoming connections or a client to perform outgoing
connections.
The personal encryptions supported by the WiFi library are WPA2 (WiFi Protected
Access) and WEP (Wired equivalent Privacy) except for WPA2 Enterprise. Arduino uses
the SPI bus to communicate with the WiFi shield.
Page 34 of 55
The library is declared as:
#include <WiFi.h>
The examples include WiFiWebClient, WiFiWebServer, etc.

Audio Library
The Audio library is compatible with the Arduino Due board only. It enables the board
to playback .wav files from the specific storage devices, such as the SD card.
It plays sounds by using the DAC0 and DAC1 pins. (Digital to analog Converter)
The library is declared as:
#include <Audio.h>
The example is a Simple Audio Player.

Audio Zero Library


It enables the board (Arduino Zero, MKR1000, and MKRZero) to playback .wav files from
the storage devices, such as the SD card.
Arduino Zero and MKR1000 board play sound by using the DAC0 pin.
The library is declared as:
#include <AudioZero.h>
The example is the Simple Audio Player Zero.

Arduino Sound Library


The Arduino Sound Library permits the board to analyze and play audio data, which is
provided by Arduino on SAMD21 based board using the I2S bus (Integrated Inter IC
Sound Bus). The SAMD21 based boards are Arduino Zero, MKR1000, MKRZero, or
Genuino Zero.
The library is declared as:
#include <AudioSound.h>
The examples include WavePlayBack, ClapDetector, WhistleDetector, etc.
Page 35 of 55
LCD (Liquid Crystal display)
The LCD (Liquid Crystal Display) is a type of display that uses the liquid crystals
for its operation.
The library that allows us to control the LCD display is called Liquid Crystal Library
which is declared as:
#include <LiquidCrystal.h>
The LCD display has a 16-pin interface. The Liquid Crystal Display has a parallel
interface. It means that the microcontroller operates several pins at once to control
the LCD display.

The 16-pins present on the LCD display are:


 RS
The Register Select (RS) pin controls the memory of the LCD in which we write the
data. We can select either the data register or the instruction register. The LCD
looks for the upcoming instruction, which is present in the instruction register.
 R/W
The Read/Write pin selects the reading or writing mode.
 E
Page 36 of 55
The Enable (E) mode is used to enable the writing to the registers. It sends the data
to the data pins when the mode is HIGH.
 D0 to D7
These are eight data pins numbered as D0, D1, D3, D3, D4, D5, D6, and D7. We can
set the state of the data pin either HIGH or LOW.
Pin 1 of the LCD is the Ground pin, and pin 2 is the VCC or the voltage source pin.
The pin 3 of the LCD is the VEE or the contrast pin. For example, we can connect
the potentiometer's output to the VEE and can adjust the contrast of the LCD.
The LED+ and LED- pins are also called as Backlight pins (Bklt+ and Bklt-).

Page 37 of 55
Program to sketch on the LCD

#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup()
{
lcd.begin(16, 2);
}
void loop()
{
lcd.setCursor(0,0);
lcd.print("Welcome User");
lcd.setCursor(5,1);
lcd.print("IICS GTB Nagar");
}

Page 38 of 55
Program to use TMP (temperature sensor) and sketch the temperature on
the LCD

#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);
void setup()
{
lcd.begin(16,2);
}
void loop()
{
int temp = analogRead(A0);
temp = temp * 0.48828125; // converting the analog volt to its temperature equivalent
lcd.setCursor(0,0);
lcd.print("Temperature :");
lcd.setCursor(2,1);
lcd.print(temp);

Page 39 of 55
lcd.print(" ");
lcd.print("C");
lcd.print(" ");
}

Page 40 of 55
Program to use TMP (temperature sensor) and light up the LED based on the
temperature

int led = 13;


int ledgreen = 11;
int ledyellow = 12;
int sensor = A0;
int value;
void setup()
{
pinMode(led, OUTPUT);
pinMode(ledgreen, OUTPUT);
pinMode(ledyellow, OUTPUT);
pinMode(sensor,INPUT);
Serial.begin(9600);
}
void loop()

Page 41 of 55
{
value = analogRead(sensor);
value = value * .48;
Serial.println(value);
if(value > 105)
{
digitalWrite(led, HIGH);
digitalWrite(ledgreen, LOW);
digitalWrite(ledyellow, LOW);
}
else if(value > 85)
{
digitalWrite(ledgreen, HIGH);
digitalWrite(led, LOW);
digitalWrite(ledyellow, LOW);
}
else if(value > 50)
{
digitalWrite(ledyellow, HIGH);
digitalWrite(ledgreen, LOW);
digitalWrite(led, LOW);
}
}

Page 42 of 55
Program to use Piezo and test the sound output

int SPEAKER = 10;


int freq = 50;
void setup()
{
pinMode(SPEAKER, OUTPUT);
}
void loop()
{
freq += 100; // add 100 to freq
if (freq > 8000)
{
noTone(SPEAKER);
freq = 50;
}

Page 43 of 55
tone(SPEAKER, freq);
delay(100);
}

Page 44 of 55
Program to increase/decrease the speed of blinking of LED based on the
Potentiometer sensor

int potPin = 2;
int ledPin = 13;
int val = 0;
void setup( )
{
pinMode(ledPin, OUTPUT);
pinMode(potPin, INPUT);
}
void loop()
{
val = analogRead(potPin);
digitalWrite(ledPin, HIGH);
delay(val);
digitalWrite(ledPin, LOW);
delay(val);
}

Page 45 of 55
Program to use MULTIMETER

int analogPin = A1;


int output;
int value;
void setup()
{
pinMode(6, OUTPUT);
}
void loop()
{
output = analogRead(analogPin);
value = map(output,0,1023,0,255);
analogWrite(6,value);
delay(2);
}

Page 46 of 55
Program to use the gas sensor, light up the LEDs based on the quality of the
air and use the speaker in case of high alert.

int const PINO_SGAS = A1;


int LED_green = 7;
int LED_yellow = 6;
int LED_orange = 5;
int LED_red = 4;
int freq = 50;
void setup()
{
pinMode(LED_green, OUTPUT);
pinMode(LED_yellow, OUTPUT);
pinMode(LED_orange, OUTPUT);
pinMode(LED_red, OUTPUT);
Serial.begin(9600);
}

Page 47 of 55
void loop()
{
int valor = analogRead(PINO_SGAS);
valor = map(valor, 300, 750, 0, 100);
digitalWrite(LED_green, HIGH);
digitalWrite(LED_yellow, valor >= -40 ? HIGH : LOW);
digitalWrite(LED_orange, valor >= -20 ? HIGH : LOW);
digitalWrite(LED_red, valor >= 0 ? HIGH : LOW);
if(valor >=0)
{
freq += 100;
if (freq > 8000)
{
noTone(12);
freq = 50;
}
tone(12, freq);
delay(100);
}
else
{
noTone(12);
}
Serial.println(valor);
delay(250);
}

Page 48 of 55
Program to use the servo motor

#include <Servo.h>
int pos = 0;
Servo servopin;
void setup()
{
servopin.attach(9);
}
void loop()
{
for (pos = 0; pos <= 180; pos += 1)
{
servopin.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1)
{
servopin.write(pos);
delay(15);
}
}

Page 49 of 55
Program to move the servo motor based on the potentiometer

#include <Servo.h>
Servo myservo;
int potpin = 0;
int val;
void setup()
{
myservo.attach(9);
}
void loop()
{
val = analogRead(potpin);
val = map(val, 0, 1023, 0, 180);
myservo.write(val);
delay(15);
}

Page 50 of 55
Program to use the Ultrasonic sensor to determine the distance of an object

#define echoPin 2
#define trigPin 3
long duration;
int distance;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
Serial.println("Ultrasonic Sensor HC-SR04 Test");
Serial.println("with Arduino UNO R3");
}
void loop()
{
digitalWrite(trigPin, LOW);

Page 51 of 55
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}

Page 52 of 55
Program to use the Ultrasonic sensor to determine the distance of an object
and light up the LED if the distance is > 100 cm

int echoPin = 2;
int trigPin =3;
long duration;
long dist;
int ledPin = 10;
void setup()
{
pinMode(trigPin,OUTPUT);
pinMode(ledPin,OUTPUT);
pinMode(echoPin,INPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
Page 53 of 55
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin,HIGH);
dist = (duration * 0.034) / 2;
if(dist > 100)
digitalWrite(ledPin,HIGH);
else
digitalWrite(ledPin,LOW);
Serial.print("Distance ");
Serial.print(dist);
Serial.println(" cm");
}

Page 54 of 55
Program to use the PIR (Passive Infrared) sensor and light up the LED when
the motion is detected in its range

void setup()
{
pinMode(3, INPUT);
pinMode(13, OUTPUT);
}
void loop()
{
if (digitalRead(3) == HIGH)
{
Serial.println("Motion Detected");
digitalWrite(13, HIGH);
}
else
digitalWrite(13, LOW);
delay(10);
}

Page 55 of 55

You might also like