Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

UNIT IV - Arduino Programming

Uploaded by

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

UNIT IV - Arduino Programming

Uploaded by

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

U21EEX04

HOME AUTOMATION

UNIT - IV

ARDUINO PROGRAMMING

Nov 19, 2024 1


U21EEX04 - HOME AUTOMATION

UNIT IV – ARDUINO PROGRAMMING

Basics of Arduino software - Arduino coding: Code


structure, data types, statement operators, control
statements, looping statements, input/output control and
sample coding for lamp and motion control-Basics of
Tinker cad simulation.

Nov 19, 2024 2


U21EEX04 - HOME AUTOMATION
UNIT IV – ARDUINO PROGRAMMING
Basics of Arduino software - Arduino coding: Code structure, data
types, statement operators, control statements, looping statements,
input/output control and sample coding for lamp and motion
control-Basics of Tinker cad simulation.

Nov 19, 2024 3


BASIC ARDUINO SOFTWARE
 Arduino Integrated Development Environment (IDE)
 Arduino IDE works, such as compiling & uploading sketches, file management, installing
dependencies and much more.
 Arduino Software (IDE) - contains a text editor for writing code, a message area, a text console,
a toolbar with buttons for common functions and a series of menus. It connects to the Arduino
hardware to upload programs and communicate with them.
 Writing Sketches
 Programs written using Arduino Software (IDE) are called sketches. These sketches are written in the
text editor and are saved with the file extension .ino.
 Additional commands are found within the five menus: File, Edit, Sketch, Tools, Help.
 Sketch
 Verify/Compile checks your sketch for errors compiling it; it will report memory usage for code and
variables in the console area.
 Upload Compiles and loads the binary file onto the configured board through the configured port.

Nov 19, 2024 4


BASIC ARDUINO SOFTWARE
 Sketchbook
 IDE uses the concept of a sketchbook: a standard place to store your programs (or sketches). The
sketches in your sketchbook can be opened from the File  Sketchbook menu or from the Open
button on the toolbar.
 Uploading
 Before uploading your sketch, you need to select the correct items from the Tools  Board and Tools
 Port menus.
 When you upload a sketch, you're using the Arduino bootloader, a small program that has
been loaded on to the microcontroller on your board. It allows you to upload code without
using any additional hardware.
 Libraries
 Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating
data. To use a library in a sketch, select it from the Sketch  Import Library menu.

Nov 19, 2024 5


BASIC ARDUINO SOFTWARE
 Serial Monitor
 This displays serial sent from the Arduino board over USB or serial connector. To send data to the
board, enter text and click on the "send" button or press enter. Choose the baud rate from the drop-
down menu that matches the rate passed to Serial.begin in your sketch.
 Boards
 The board selection has two effects: it sets the parameters (e.g. CPU speed and baud rate) used when
compiling and uploading sketches.

Nov 19, 2024 6


BASIC ARDUINO SOFTWARE
 Arduino Hardware
 While all Arduino boards differ from each other, there are several key components that can be found
on practically any Arduino.

Nov 19, 2024 7


BASIC ARDUINO SOFTWARE
 Arduino API
 Sketch − The first new terminology is the Arduino program called “sketch”.
 Arduino programs can be divided in three main parts: Structure, Values (variables and constants),
and Functions.
 The Arduino API can be divided into three main parts: functions, variables and structure:
 Functions: for controlling the Arduino board and performing computations. For example, to read or
write a state to a digital pin, map a value or use serial communication.
 Variables: the Arduino constants, data types and conversions. E.g. int, boolean, array.
 Structure: the elements of the Arduino (C++) code such as sketch (loop(), setup()), control structure
(if, else, while, for), arithmetic operators (multiplication, addition, subtraction), comparison
operators such as == (equal to), != (not equal to), > (greater than).
 The Arduino API can be described as a simplification of the C++ programming language, with a lot
of additions for controlling the Arduino hardware.

Nov 19, 2024 8


BASIC ARDUINO SOFTWARE
 Program Structure
 The absolute minimum requirement of an Arduino program is the use of two functions: void setup()
and void loop(). The "void" indicates that nothing is returned on execution.
 void setup() - this function executes only once, when the Arduino is powered on. Here we define
things such as the mode of a pin (input or output), the baud rate of serial communication or the
initialization of a library.
 void loop() - this is where we write the code that we want to execute over and over again, such as
turning on/off a lamp based on an input, or to conduct a sensor reading every X second.
 The above functions are always required in an Arduino sketch, but you are of course able to add
several more functions, which is useful for longer programs.
 The "Sketch"
 In the Arduino project, a program is referred to as a "sketch". A sketch is a file that you write
your program inside. It has the .ino extension, and is always stored in a folder of the same name.
 The folder can include other files, such as a header file, that can be included in your sketch.

Nov 19, 2024 9


BASIC ARDUINO SOFTWARE
 A Typical Workflow
 To upload code to an Arduino board using the IDE, one typically does the following:
 1. Install your board - this means installing the right "package" for your board. Without the package,
you can simply not use your board. Installing is done directly in the IDE, and is a quick and easy
operation.
 2. Create a new sketch - a sketch is your main program file. Here we write a set of instructions we
want to execute on the microcontroller.
 3. Compile your sketch - the code we write is not exactly how it looks like when uploaded to our
Arduino: compiling code means that we check it for errors, and convert it into a binary file (1s and
0s). If something fails, you will get this in the error console.
 4. Upload your sketch - once the compilation is successful, the code can be uploaded to your board.
In this step, we connect the board to the computer physically, and select the right serial port.
 5. Serial Monitor (optional) - for most Arduino projects, it is important to know what's going on on
your board. The Serial Monitor tool available in all IDEs allow for data to be sent from your board to
your computer.

Nov 19, 2024 10


ARDUINO PROGRAM STRUCTURE
 Sketch

Nov 19, 2024 11


ARDUINO - DATA TYPES
 The Arduino - Data Types
 Data types in C refers to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in the storage and how the bit
pattern stored is interpreted.
 The following provides all the data types that you will use during Arduino programming.
 Void Boolean char Unsigned char byte int Unsigned int word
 long Unsigned long short float double array String-char array String-object
 void
 The void keyword is used only in function declarations. It indicates that the function is expected
to return no information to the function from which it was called.
 Example
 Void loop ( ) {
 // rest of the code
 }
Nov 19, 2024 12
ARDUINO - DATA TYPES
 Constants
 HIGH | LOW, INPUT | OUTPUT, true | false, Floating Point Constants, Integer Constants
 Conversion
 (unsigned int), (unsigned long), byte(), char(), float(), int(), long(), word()
 Data Types
 Array, bool, Boolean, byte, char, double, float, int, long, short, size_t, string, String(), unsigned char,
unsigned int, unsigned long, void, word
 Variables & Constants
 Variables in C programming language, which Arduino uses, have a property called scope. A scope is a
region of the program and there are three places where variables can be declared.
 Inside a function or a block, which is called local variables.
 In the definition of function parameters, which is called formal parameters.
 Outside of all functions, which is called global variables.

Nov 19, 2024 13


ARDUINO - DATA TYPES
 FUNCTIONS
 For controlling the Arduino board and performing computations.
 Digital I/O : digitalRead(), digitalWrite(), pinMode()
 Analog I/O : analogRead(), analogReference(), analogWrite()
 Advanced I/O : noTone(), pulseIn(), pulseInLong(), shiftIn(), shiftOut(), tone()
 Time : delay(), delayMicroseconds(), micros(), millis()
 Math : abs(), constrain(), map(), max(), min(), pow(), sq(), sqrt()
 Trigonometry : cos(), sin(), tan()
 Characters : isAlpha(), isAlphaNumeric(), isAscii(), isControl(), isDigit(), isGraph(),
isHexadecimalDigit(), isLowerCase(), isPrintable(), isPunct(), isSpace(), isUpperCase(),
isWhitespace()
 Random Numbers : random(), randomSeed(), Bits and Bytes, bit(), bitClear(), bitRead(), bitSet(),
bitWrite(), highByte(), lowByte()

Nov 19, 2024 14


ARDUINO - DATA TYPES
 Control Structure : break, continue, do...while, for, goto, if, return, switch...case, while
 Comparison Operators : != (not equal to), < (less than), <= (less than or equal to), == (equal to)
> (greater than), >= (greater than or equal to)
 Further Syntax : #define (define), #include (include), /* */ (block comment), // (single line
comment), ; (semicolon), {} (curly braces)

Nov 19, 2024 15


ARDUINO –COMPARISON STATEMENTS OR OPERATORS
 Statement/Comparison Operators :
 The statements being evaluated inside the parentheses require the use of one or more operators
shown below.
x == y (x is equal to y)
x != y (x is not equal to y)
x < y (x is less than y)
x > y (x is greater than y)
x <= y (x is less than or equal to y)
x >= y (x is greater than or equal to y)
 Beware of accidentally using the single equal sign (e.g. if (x = 10) ). The single equal sign is the
assignment operator, and sets x to 10 (puts the value 10 into the variable x). Instead use the double
equal sign (e.g. if (x == 10) ), which is the comparison operator, and tests whether x is equal to 10 or
not. The latter statement is only true if x equals 10, but the former statement will always be true.

Nov 19, 2024 16


ARDUINO – CONTROL STRUCTURES OR STATEMENTS
 Control Structure /Statement:
 The control statements are break, continue, goto, return
 Break : break is used to exit from a for, while or do…​while loop, bypassing the normal loop condition.
It is also used to exit from a switch case statement.
 Example Code
 In the following code, the control exits the for loop when the sensor value exceeds the threshold.
int threshold = 40;
for (int x = 0; x < 255; x++) {
analogWrite(PWMpin, x);
sens = analogRead(sensorPin);
if (sens > threshold) { // bail out on sensor detect
x = 0;
break;
}
delay(50);
}

Nov 19, 2024 17


ARDUINO – CONTROL STATEMENTS
 continue :
 The continue statement skips the rest of the current iteration of a loop (for, while, or do…​while). It
continues by checking the conditional expression of the loop, and proceeding with any subsequent
iterations.
 Example Code
 The following code writes the value of 0 to 255 to the PWM pin, but skips the values in the range of
41 to 119.
for (int x = 0; x <= 255; x ++) {
if (x > 40 && x < 120) { // create jump in values
continue;
}
analogWrite(PWMpin, x);
delay(50);
}

Nov 19, 2024 18


ARDUINO – CONTROL STATEMENTS
 goto :
 Transfers program flow to a labeled point in the program
 Syntax
label:
goto label; // sends program flow to the label.
 Example Code
if (analogRead(0) > 250) {
goto bailout;
}
bailout:
// more statements ...

Nov 19, 2024 19


ARDUINO – CONTROL STATEMENTS
 return :
 Terminate a function and return a value from a function to the calling function, if desired.
 Syntax
return;
return value;
 Example Code
 A function to compare a sensor input to a threshold
int checkSensor() {
if (analogRead(0) > 400) {
return 1;
}
else {
return 0;
}
}

Nov 19, 2024 20


ARDUINO – LOOPING STATEMENTS
 The looping statements are if…else…, for, while, do…while…, switch…case
 if :
 The if statement checks for a condition and executes the following statement or set of statements if
the condition is 'true'.
 Syntax
if (condition) {
//statement(s)
}
 condition: a boolean expression (i.e., can be true or false).
 Example Code
 The brackets may be omitted after an if statement. If this is done, the next line (defined by the
semicolon) becomes the only conditional statement.

if (x > 120) digitalWrite(LEDpin, HIGH);

Nov 19, 2024 21


ARDUINO – LOOPING STATEMENTS
 else :
 The if…​else allows greater control over the flow of code than the basic if statement, by allowing
multiple tests to be grouped. An else clause (if at all exists) will be executed if the condition in the if
statement results in false. The else can proceed another if test, so that multiple, mutually exclusive
tests can be run at the same time.
 Syntax
if (condition1) {
// do Thing A
}
else if (condition2) {
// do Thing B
}
else {
// do Thing C
}

Nov 19, 2024 22


ARDUINO – LOOPING STATEMENTS
 else :
 Example Code
 Below is an extract from a code for temperature sensor system
if (temperature >= 70) {
// Danger! Shut down the system.
}
else if (temperature >= 60) { // 60 <= temperature < 70
// Warning! User attention required.
}
else { // temperature < 60
// Safe! Continue usual tasks.
}

Nov 19, 2024 23


ARDUINO – LOOPING STATEMENTS
 for :
 The for statement is used to repeat a block of statements enclosed in curly braces. An increment
counter is usually used to increment and terminate the loop. The for statement is useful for any
repetitive operation, and is often used in combination with arrays to operate on collections of
data/pins.
 Syntax
for (initialization; condition; increment) {
// statement(s);
}
 initialization: happens first and exactly once.
 condition: each time through the loop, condition is tested; if it’s true, the statement block, and the
increment is executed, then the condition is tested again. When the condition becomes false, the loop
ends.
 increment: executed each time through the loop when condition is true.

Nov 19, 2024 24


ARDUINO – LOOPING STATEMENTS
 for :
 Example Code
// Dim an LED using a PWM pin
int PWMpin = 10; // LED in series with 470 ohm resistor on pin 10
void setup() {
// no setup needed
}
void loop() {
for (int i = 0; i <= 255; i++) {
analogWrite(PWMpin, i);
delay(10);
}
}

Nov 19, 2024 25


ARDUINO – LOOPING STATEMENTS
 while :
 A while loop will loop continuously, and infinitely, until the expression inside the parenthesis ()
becomes false. Something must change the tested variable, or the while loop will never exit. This
could be in your code, such as an incremented variable, or an external condition, such as testing a
sensor.
 Syntax
while (condition) {
// statement(s)
}
 condition: a boolean expression that evaluates to true or false.
 Example Code
var = 0;
while (var < 200) {
// do something repetitive 200 times
var++;
}

Nov 19, 2024 26


ARDUINO – LOOPING STATEMENTS
 do...while :
 The do…​while loop works in the same manner as the while loop, with the exception that the
condition is tested at the end of the loop, so the do loop will always run at least once.
 Syntax
do {
// statement block
} while (condition);
 condition: a boolean expression that evaluates to true or false.
 Example Code
int x = 0;
do {
delay(50); // wait for sensors to stabilize
x = readSensors(); // check the sensors
} while (x < 100);

Nov 19, 2024 27


ARDUINO – LOOPING STATEMENTS
 switch...case :
 A switch statement compares the value of a variable to the values specified in case statements. When
a case statement is found whose value matches that of the variable, the code is run.
 The break keyword exits at the end of each case. Without “break” statement, the switch statement
will continue executing the following expressions until a break, or the end of the switch statement is
reached.
 Syntax
switch (var) {
case label1:
// statements
break;
case label2:
// statements
break;
default:
// statements
break;
}
Nov 19, 2024 28
ARDUINO – LOOPING STATEMENTS
 switch...case :
 Example Code
switch (var) {
case 1:
//do something when var equals 1
break;
case 2:
//do something when var equals 2
break;
default:
// if nothing else matches, do the default
// default is optional
break;
}

Nov 19, 2024 29


ARDUINO – INPUT/OUTPUT CONTROL
 There are digital and analog input-output controls
 Digital Input-Output
 The digital input-output control statements are given below.
 digitalRead()
 digitalWrite()
 pinMode()
 Analog Input-Output
 The analog input-output control statements are given below.
 analogRead()
 analogReference
 analogWrite()

Nov 19, 2024 30


ARDUINO – INPUT/OUTPUT CONTROL
 digitalRead()
 Reads the value from a specified digital pin, either HIGH or LOW.
 Syntax
digitalRead(pin)
 Example Code
 Sets pin 13 to the same value as pin 7, declared as an input.
int ledPin = 13; // LED connected to digital pin 13
int inPin = 7; // pushbutton connected to digital pin 7
int val = 0; // variable to store the read value
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output
pinMode(inPin, INPUT); // sets the digital pin 7 as input
}
void loop() {
val = digitalRead(inPin); // read the input pin
digitalWrite(ledPin, val); // sets the LED to the button's value
}

Nov 19, 2024 31


ARDUINO – INPUT/OUTPUT CONTROL
 digitalWrite()
 Write a HIGH or a LOW value to a digital pin.
 If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the
corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.
 Syntax
digitalWrite(pin, value)
 Example Code
 The code makes the digital pin 13 an OUTPUT and toggles it by alternating between HIGH and LOW at one
second pace.
void setup() {
pinMode(13, OUTPUT); // sets the digital pin 13 as output
}
void loop() {
digitalWrite(13, HIGH); // sets the digital pin 13 on
delay(1000); // waits for a second
digitalWrite(13, LOW); // sets the digital pin 13 off
delay(1000); // waits for a second
}
Nov 19, 2024 32
ARDUINO – INPUT/OUTPUT CONTROL
 pinMode()
 Configures the specified pin to behave either as an input or an output. See the Digital Pins page for
details on the functionality of the pins.
 As of Arduino 1.0.1, it is possible to enable the internal pullup resistors with the mode
INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pullups.
 Syntax
pinMode(pin, mode)
 Example Code
 The code makes the digital pin 13 OUTPUT and Toggles it HIGH and LOW
void setup() {
pinMode(13, OUTPUT); // sets the digital pin 13 as output
}
void loop() {
digitalWrite(13, HIGH); // sets the digital pin 13 on
delay(1000); // waits for a second
digitalWrite(13, LOW); // sets the digital pin 13 off
delay(1000); // waits for a second
}
Nov 19, 2024 33
ARDUINO – INPUT/OUTPUT CONTROL
 Analog Input-Output
 analogRead()
 Reads the value from the specified analog pin. Arduino boards contain a multichannel, 10-bit analog
to digital converter. This means that it will map input voltages between 0 and the operating
voltage(5V or 3.3V) into integer values between 0 and 1023. On an Arduino UNO, for example, this
yields a resolution between readings of: 5 volts / 1024 units or, 0.0049 volts (4.9 mV) per unit. See
the table below for the usable pins, operating voltage and maximum resolution for some Arduino
boards.
 Syntax
analogRead(pin)

Nov 19, 2024 34


ARDUINO – INPUT/OUTPUT CONTROL
 analogRead()
 Example Code
 The code reads the voltage on analogPin and displays it.
int analogPin = A3; // 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() {
Serial.begin(9600); // setup serial
}
void loop() {
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}

Nov 19, 2024 35


ARDUINO – INPUT/OUTPUT CONTROL
 analogWrite()
 Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or
drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady
rectangular wave of the specified duty cycle until the next call to analogWrite() (or a call to
digitalRead() or digitalWrite()) on the same pin.
 Syntax
analogWrite(pin, value)
 Example Code
Sets the output to the LED proportional to the value read from the potentiometer.
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
} 2024
Nov 19, 36
ARDUINO – INPUT/OUTPUT CONTROL
 analogReference()
 Configures the reference voltage used for analog input (i.e. the value used as the top of the input
range). The options are:
 Arduino AVR Boards (Uno, Mega, Leonardo, etc.).
 Syntax
analogReference(type)
 Returns: Nothing
 Notes and Warnings: After changing the analog reference, the first few readings from analogRead()
may not be accurate.

Nov 19, 2024 37


ARDUINO – INPUT/OUTPUT CONTROL
 delay ( )
 The delay () function is a blocking function to pause a program from doing a task during the specified
duration in milliseconds.
 Example: - delay (2000)
 Where, 1 sec = 1000millisecond. Hence, it will provide a delay of 2 seconds.
 Code:
digitalWrite (13, HIGH);
delay (2000);
digitalWrite (13, LOW);
delay (1000);

Nov 19, 2024 38


ARDUINO – INPUT/OUTPUT CONTROL
 PWM (Pulse Width Modulation)
 PWM, is a technique for getting analog results with digital means.
 Digital control is used to create a square wave, a signal switched between on and off. This on-
off pattern can simulate voltages in between the full Vcc of the board (e.g., 5 V on UNO) and off (0
Volts) by changing the portion of the time the signal spends on versus the time that the signal spends
off.
 The duration of "on time" is called the pulse width. To get varying analog values, you change, or
modulate, that pulse width.
 If you repeat this on-off pattern fast enough with an LED for example, the result is as if the signal is a
steady voltage between 0 and Vcc controlling the brightness of the LED.
 The Fading example demonstrates the use of analog output (PWM) to fade an LED. It is available in
the File  Sketchbook  Examples  Analog menu of the Arduino software.

Nov 19, 2024 39


ARDUINO – INPUT/OUTPUT CONTROL
 PWM Control – Control the brightness of the LED
int pin=9;
void setup() {
pinMode(pin, OUTPUT);
}
void loop() { analogWrite(pin, 127);
digitalWrite(pin, HIGH); delay(1000);
delay(1000); analogWrite(pin, 191);
delay(1000);
digitalWrite(pin, LOW);
analogWrite(pin, 255);
delay(2000); delay(1000);
analogWrite(pin, 64); analogWrite(pin, 0);
delay(1000); delay(1000);
}

Nov 19, 2024 40


ARDUINO – INPUT/OUTPUT CONTROL
 PWM to Control the Angle of Rotation of Servo
 The angle of servo motor rotation is determined by the duration of a pulse that is applied to the
control wire. The servo expects a pulse every 20 milliseconds (0.02 seconds).
 The length of the pulse will determine how far the motor rotates. A 1.5-millisecond pulse, for
example, makes the motor turn to the 90-degree position (often called the neutral position).
 If the pulse is shorter than 1.5ms, the motor turns the shaft lesser than 90 degrees. If the pulse is
longer than 1.5ms, the shaft turns closer to180 degrees

Nov 19, 2024 41


ARDUINO - PROGRAMMING
Arduino programs have a minimum of 2 blocks,
 Preparation & Execution
Each block has a set of statements enclosed in curly braces:
void setup( )
{
statements-1; ……
statement-n;
}
void loop ( )
{
statement-1; ……….
statement-n;
}

Nov 19, 2024 42


ARDUINO - PROGRAMMING
 FUNCTIONS
 The “void setup()" section is widely used to initialize variables, pin modes, set the serial baud
rate and related. The software only goes though the section once.
 The “void loop()" section is the part of the code that loops back onto itself and is the main part of
the code.
 Serial Communication
 The Arduino board can communicate at various baud ("baud rates").
 A baud is a measure of how many times the hardware can send 0s and 1s in a second.
 The baud rate must be set properly for the board to convert incoming and outgoing information
to useful data.
 If your receiver is expecting to communicate at a baud rate of 2400, but your transmitter is
transmitting at a different rate (for example 9600), the data you get will not make sense.
 To set the baud rate, use the following code:
void setup() {
Serial.begin(9600);
}
Nov 19, 2024 43
ARDUINO - PROGRAMMING
 Program Execution
 From Software to Hardware
 The platform is comprised of both software and hardware. The two work in tandem to run a complex
operating system.
 Code → Compile → Upload → Run
 Serial Monitor and Serial Plotter
 Arduino serial monitor can be opened by clicking on the magnifying glass icon on the upper right side
of the IDE or under tools.
 The serial monitor is used mainly for interacting with the Arduino board using the computer, and is a
great tool for real-time monitoring and debugging.

Nov 19, 2024 44


ARDUINO - PROGRAMMING
 Serial Monitor and Serial Plotter

Nov 19, 2024 45


ARDUINO - PROGRAMMING
 Arduino IDE: This is the Arduino IDE and is the place where all the programming will happen.

 Serial Monitor: When the board is connected, this will display the serial information of your Arduino
Nov 19, 2024 46
ARDUINO - PROGRAMMING
 To connect your Arduino to your computer.
 Once the board is connected, you need to go Tools then Board then finally select Arduino Uno.

Nov 19, 2024 47


ARDUINO - PROGRAMMING
 Blinking LED
 Steps in building a breadboard connection:
 Step-1: Connect the Arduino to the Windows / Mac / Linux system via a USB cable
 Step-2: Connect the 13th digital pin of Arduino to the positive power rail of the breadboard and GND
to the negative
 Step-3: Connect the positive power rail to the terminal strip via a 1K ohm resistor
 Step-4: Fix the LED to the ports below the resistor connection in the terminal strip
 Step-5: Close the circuit by connecting the cathode (the short chord) of the LED to the negative
power strip of the breadboard

Nov 19, 2024 48


ARDUINO - PROGRAMMING

Nov 19, 2024 49


ARDUINO - PROGRAMMING
Program
void setup ( )
{
pinMode (LED, OUTPUT); //Declaring pin 13 as output pin
}
void loop( ) // The loop function runs again and again
{
digitalWrite (LED, HIGH); //Turn ON the LED
delay(1000); //Wait for 1sec
digitalRead (LED, LOW); // Turn off the LED
delay(1000); // Wait for 1sec
}

Nov 19, 2024 50


ARDUINO - PROGRAMMING
Arduino program for LED blink
void setup ( )
{
pinMode (13, OUTPUT); //Declaring pin 13 as output pin
}

void loop( ) // The loop function runs again and again


{
digitalWrite (13, HIGH); //Turn ON the LED
delay(1000); //Wait for 1sec
digitalRead (13, LOW); // Turn off the LED
delay(1000); // Wait for 1sec
}

Nov 19, 2024 51


ARDUINO - PROGRAMMING
Fade-in and fade-out the LED
The step for the LED bling experiment are the same as those followed for building the breadboard circuit
except that in step-2, you connect the 9th digital pin to the positive power rail of the breadboard.
int brightness = 0; // Brightness of LED is initially set to 0
int fade = 5; // By how many points the LED should fade
void setup()
{
pinMode(led, OUTPUT); //pin 10 is set as output pin
}
void loop() // The loop function runs again and again
{
analogWrite(led, brightness); // set the brightness of LED
brightness = brightness + fade; //Increase the brightness of LED by 5 points
if (brightness <= 0 || brightness >= 255) // check the level of brightness
{
fade = -fade;
}
delay(30); // Wait for 30 milliseconds
}

Nov 19, 2024 52


CONTROL A LAMP USING ARDUINO
 Blinking LED
 Steps in building a breadboard connection:
 Step-1: Connect the Arduino to the Windows / Mac / Linux system via a USB cable
 Step-2: Connect the 13th digital pin of Arduino to the positive power rail of the breadboard and GND
to the negative
 Step-3: Connect the positive power rail to the terminal strip via a 1K ohm resistor
 Step-4: Fix the LED to the ports below the resistor connection in the terminal strip
 Step-5: Close the circuit by connecting the cathode (the short chord) of the LED to the negative
power strip of the breadboard

Nov 19, 2024 53


CONTROL A LAMP USING ARDUINO
 Control Light with Arduino and PIR Motion Sensor
 Components Required: 1. Arduino Uno, 2. PIR motion sensor, 3. Relay module, 4. Some Wires, 5.
Lamp
 PIR sensor:
 The PIR sensor stands for Passive Infrared sensor. It is a low cost sensor which can detect the
presence of Human beings or animals. There are two important materials present in the sensor one is
the pyroelectric crystal which can detect the heat signatures from a living organism
(humans/animals) and the other is a Fresnel lenses which can widen the range of the sensor. Also the
PIR sensor modules provide us some options to adjust the working of the sensor.
 The PIR sensor has three pins : 1. VCC, 2. GND, 3. OUT
 Powered the PIR sensor using he 5V Rail of the Arduino. The output pin of the PIR Sensor is
connected to the 4thdigital pin. Then, you have to wire the ''GND'' to the Arduino's ''GND‘’.
 Use relay for controlling AC light because the Arduino cannot control high volt , but a relay can do this
job, so using relay as switch to control high power devices.

Nov 19, 2024 54


CONTROL A LAMP USING ARDUINO
 Control Light with Arduino and PIR Motion Sensor
 There are two ways to assembly the relay connection :
 1. NC = Normally Closed Connection 2. NO = Normally Open Connection.
 To wire the relay's ''OUT'' to the 8th digital pin of the arduino uno. Then the relay's ''GND'' to the
arduino's ''GND'' and ''VCC'' to the ''VCC‘’.

Nov 19, 2024 55


CONTROL A LAMP USING ARDUINO
 Control Light with Arduino and PIR Motion Sensor
 Arduino Programe/Code :
int lamp = 8; // choose the pin for the RELAY
int inputPin = 4; // choose the input pin (for PIR sensor)
int val = 0; // variable for reading the pin status
void setup() {
pinMode(lamp, OUTPUT); // declare lamp as output
pinMode(inputPin, INPUT); // declare sensor as input
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin); // read input value
Serial.println(val);
if( val== 1) {
digitalWrite(lamp,HIGH); // turn ON the lamp
} else {
digitalWrite(lamp,LOW); // turn OFF the lamp
}
}

Nov 19, 2024 56


CONTROL A LAMP USING ARDUINO
 Control Light with Arduino and PIR Motion Sensor

Nov 19, 2024 57


CONTROL A LAMP USING NODEMCU
 Control Light with Arduino and PIR Motion Sensor
 Step 1: Materials Required :
 ESP8266 NodeMCU, Breadboard, LED, Jumper Wires, Arduino IDE
 Step 2: Installing NodeMCU Board Package

Nov 19, 2024 58


CONTROL A LAMP USING NODEMCU
 Open up Arduino IDE. Go to Files-> Preferences. Enter
 http://arduino.esp8266.com/stable/package_esp8266... into Additional Board Manager URLs field
 Now go to Tools->Boards->Board Manager, and search for ESP8266 and install the package.
 Step 3: Pin Connections
 D7 of NodeMCU to LED's +ve.
 G of NodeMCU to LED's -ve.

Nov 19, 2024 59


CONTROL A LAMP USING NODEMCU
 Step 4: Program
 In code, change ssid to your ssid name
 and Password to your SSID's password
 const char* ssid = “MCU";//your ssid
 const char* password = “12345678";//Your Password

Nov 19, 2024 60


CONTROL A LAMP USING NODEMCU
 Step 5: Controlling the LED
 Now open up your Serial Monitor, and note down the URL.
 Now put the URL in your phone's browser.
 A page will open having two buttons ON and OFF.
 If everything is correct when you press ON the LED will light up and when you press OFF the LED will
turn off.

Nov 19, 2024 61


BASICS OF TINKERCAD SIMULATION
 Tinkercad is an online tool that allows users to design circuits.
 Benefits and features of Tinkercad for circuit design :
 Users can begin with a starter circuit or build their own by using premade wire components.
 Virtual-circuits are a great way to learn and tinker before making it in real life.
 Built-in Code blocks or custom C++ can run circuit components.
 Users can tweak and further define them until they achieve their desired result.
 Simulate and programme Arduino and breadboard components.
 Use standard modules to build complex circuits.
 Create and explore circuits, then export to PCB design software, such as Autodesk Fusion 360.

Nov 19, 2024 62


BASICS OF TINKERCAD SIMULATION
 Tinkercad Circuits:
 It is a browser-based electronic circuit simulator that supports Arduino Uno microcontrollers,
Micro:bit boards, or ATtiny chips.
 Code can be created using graphical CodeBlocks, pieces of code that can be easily arranged with the
mouse, or text-based code. Digi-Key praised Tinkercad in a 2022 article for its intuitive and fast tool
capabilities, making it ideal for beginners.
 The program offers pre-built circuits called "Starters" or circuits that can be built using separate
components.
 Tinkercad comes with built-in libraries for popular components, including the Adafruit Neopixel,
Arduino Servo, and I2C display libraries. However, custom libraries cannot be selected or uploaded.
The simulator also supports analog components that are fully simulated.
 Despite being an entry-level tool for programming and electronics, Tinkercad offers advanced
features such as multi-board simulation and complex analog circuits for experienced users.

Nov 19, 2024 63


BASICS OF TINKERCAD SIMULATION
 Creating an Account in Tinkercad
 The first step is to create an account in Tinkercad. You can access the website by clicking here.
 After visiting the website, click on SIGN UP to create a new account. Alternatively, you can directly
login if you already have an account.
 Next, click on CREATE A PERSONAL ACCOUNT to start with your account creation.
 After that, you will be provided with several options to create an account.
 You can either sign-up using your email ID, or sign in using your Google/Apple ID.
 Sign-in Interface
 Once you sign in to the Tinkercad platform, you will be able to see the following interface.
 Subsequently, click on the TINKER drop-down menu
 Tinkercad user-interface
 As a result, you will be able to see many options. In order to get used to the platform, click on
LEARNING CENTER.
 Here, you will get lots of tutorials on how to use various sections of the platform.

Nov 19, 2024 64


BASICS OF TINKERCAD SIMULATION
 Creating an Account in Tinkercad

Nov 19, 2024 65


BASICS OF TINKERCAD SIMULATION
 Creating your project in Tinkercad
 Now, in order to start making your circuit, click on the CIRCUITS option.
 Following that, click on the CREATE NEW CIRCUIT option.

Nov 19, 2024 66


BASICS OF TINKERCAD SIMULATION
 Creating your project in Tinkercad
 Now, let us make a simple Arduino simulation to make an LED blink.
 The right-most part is the components section. Firstly, type in Arduino in the search bar. Drag out the
Arduino into the workspace.

Nov 19, 2024 67


BASICS OF TINKERCAD SIMULATION
 Similarly, choose a breadboard and an LED and drag them onto the workspace.
 After placing the main components, the workspace would look as shown below. Click the ZOOM TO
FIT (square icon) on the top-left to view the entire setup.

Nov 19, 2024 68


BASICS OF TINKERCAD SIMULATION
 Firstly, connect the cathode of the LED to the ground (GND) terminal of Arduino. Next, connect the
anode of the LED to any of the digital pins (for eg. 9) of the Arduino. In order to limit the current flow
through the LED, add a resistor (for eg. 1kΩ ) between the connection from the anode to the digital
pin.

Nov 19, 2024 69


BASICS OF TINKERCAD SIMULATION
 Coding the Arduino
 Now, let’s dive into the coding part. For coding the Arduino, Tinkercad provides us with 3 options –
BLOCKS, BLOCKS+TEXT, and TEXT. In this tutorial, we will be focusing on the TEXT option i.e coding
using C++.
 First, click on the CODE option on the top right side of the interface. Then, select the TEXT option of
the Edit mode. As a result, a default template code will be visible as shown below

Nov 19, 2024 70


BASICS OF TINKERCAD SIMULATION
 Coding the Arduino
 First, let’s look at the setup() function. The code that we write within the setup() function only runs
once. Here, we use the pinMode() function to configure a pin as input/output.
 Next, let’s look at the loop() function. The code that we write within the loop() function keeps on
getting executed until we stop the simulation. The digitalWrite() function is used to write (assign) a
HIGH/LOW value to a pin. We do this in order to turn the LED ON/OFF respectively. Remember to
replace the LED_BUILTIN parameter with the pin number (9).
 We use the delay() function between the digitalWrite() functions in order to make the blinking action
visible. So here, we use 1000 milliseconds as the delay time.

Nov 19, 2024 71


BASICS OF TINKERCAD SIMULATION
 Coding the Arduino

Nov 19, 2024 72


ARDUINO PROGRAMMING RESOURCES
Arduino Programming Links
https://www.javatpoint.com/arduino-coding-basics
Getting Started with Arduino | Arduino Documentation
Arduino Reference - Arduino Reference
Arduino - Data Types (tutorialspoint.com)
https://www.javatpoint.com/iot-project-controlling-light-using-nodemcu-relay-wifi
Basics of Arduino (TINKERCAD) : 15 Steps (with Pictures) – Instructables

Nov 19, 2024 73

You might also like