Arduino Code S22
Arduino Code S22
Page 1 of 55
Power USB
Arduino board is powered by using the USB cable.
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).
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.
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);
}
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
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)
Page 9 of 55
Program to turn on the LED and turn off the LED by pressing the push button
(State Change Detection)
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);
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);
}
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);
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");
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());
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");
}
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)
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>
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.
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.
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
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
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
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.
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