0% found this document useful (0 votes)
3 views30 pages

Arduino

Uploaded by

as987hdf6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

Arduino

Uploaded by

as987hdf6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Arduino - I/O Functions

pinMode(3,INPUT) ; // set pin to input without using built in pull up


resistor pinMode(5,INPUT_PULLUP) ; // set pin to input using built
in pull up resistor

pinMode() Function
The pinMode() function is used to configure a specific pin to behave either
as an input or an output. It is possible to enable the internal pull-up
resistors with the mode INPUT_PULLUP. Additionally, the INPUT mode
explicitly disables the internal pull-ups.

pinMode() Function Syntax


Void setup () { pinMode (pin , mode); }
•pin − the number of the pin whose mode you wish to set
•mode − INPUT, OUTPUT, or INPUT_PULLUP.
int button = 5 ; // button connected to pin 5
int LED = 6; // LED connected to pin 6

void setup () {
pinMode(button , INPUT_PULLUP);
// set the digital pin as input with pull-up resistor
pinMode(button , OUTPUT); // set the digital pin as output
}

void setup () {
If (digitalRead(button ) == LOW) // if button pressed {
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}
}
digitalWrite() Function
The digitalWrite() function is used to 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. If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable
(LOW) the internal pullup on the input pin. It is recommended to set
the pinMode() to INPUT_PULLUP to enable the internal pull-up resistor.

digitalWrite() Function Syntax


Void loop() { digitalWrite (pin ,value); }
•pin − the number of the pin whose mode you wish to set
•value − HIGH, or LOW.
int LED = 6; // LED connected to pin 6

void setup () {
pinMode(LED, OUTPUT); // set the
digital pin as output
}

void setup () {
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}
analogRead( ) function
Arduino is able to detect whether there is a voltage applied to one of its pins and report it
through the digitalRead() function. There is a difference between an on/off sensor (which
detects the presence of an object) and an analog sensor, whose value continuously changes.
In order to read this type of sensor, we need a different type of pin.

int analogPin = 3;//potentiometer wiper


(middle terminal)
analogRead() function Syntax // connected to analog pin 3
analogRead(pin);
•pin − the number of the analog input pin to
int val = 0; // variable to store the value read
read from (0 to 5 on most boards, 0 to 7 on
the Mini and Nano, 0 to 15 on the Mega) void setup() {
Serial.begin(9600); // setup serial
}
void loop() {
val = analogRead(analogPin); // read the input
pin
Serial.println(val); // debug value
}
Arduino - Advanced I/O Function

analogReference() Function
Configures the reference voltage used for analog input (i.e. the value used as the top of the
input range). The options are −
•DEFAULT − The default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on
3.3V Arduino boards)
•INTERNAL − An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328
and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
•INTERNAL1V1 − A built-in 1.1V reference (Arduino Mega only)
•INTERNAL2V56 − A built-in 2.56V reference (Arduino Mega only)
•EXTERNAL − The voltage applied to the AREF pin (0 to 5V only) is used as the reference
Arduino - Character Functions

1 int isdigit( int c )


Returns 1 if c is a digit and 0 otherwise.

2 int isalpha( int c )


Returns 1 if c is a letter and 0 otherwise.

3 int isalnum( int c )


Returns 1 if c is a digit or a letter and 0 otherwise.

int isxdigit( int c )


4 Returns 1 if c is a hexadecimal digit character and 0 otherwise.
(See Appendix D, Number Systems, for a detailed explanation of binary, octal,
decimal and hexadecimal numbers.)

5 int islower( int c )


Returns 1 if c is a lowercase letter and 0 otherwise.
void setup () {
Serial.begin (9600);
Serial.print ("According to isdigit:\r");
Serial.print (isdigit( '8' ) ? "8 is a": "8 is not a");
Serial.print (" digit\r" );
Serial.print (isdigit( '8' ) ?"# is a": "# is not a") ;
Serial.print (" digit\r");
Serial.print ("\rAccording to isalpha:\r" );
Serial.print (isalpha('A' ) ?"A is a": "A is not a");
Serial.print (" letter\r");
Serial.print (isalpha('A' ) ?"b is a": "b is not a");
Serial.print (" letter\r");
Serial.print (isalpha('A') ?"& is a": "& is not a");
Serial.print (" letter\r");
Serial.print (isalpha( 'A' ) ?"4 is a":"4 is not a");
Serial.print (" letter\r");
Serial.print ("\rAccording to isalnum:\r");
Serial.print (isalnum( 'A' ) ?"A is a" : "A is not a" );
Serial.print (" digit or a letter\r" );
Serial.print (isalnum( '8' ) ?"8 is a" : "8 is not a" ) ;
Serial.print (" digit or a letter\r");
Serial.print (isalnum( '#' ) ?"# is a" : "# is not a" );
Serial.print (" digit or a letter\r");
Serial.print ("\rAccording to isxdigit:\r");
Serial.print (isxdigit( 'F' ) ?"F is a" : "F is not a" );
Serial.print (" hexadecimal digit\r" );
Serial.print (isxdigit( 'J' ) ?"J is a" : "J is not a" ) ;
Serial.print (" hexadecimal digit\r" );
Serial.print (isxdigit( '7' ) ?"7 is a" : "7 is not a" ) ;
According to isdigit:
serial.print (" hexadecimal digit\r" ); 8 is a digit
Serial.print (isxdigit( '$' ) ? "$ is a" : "$ is # is not a digit
According to isalpha:
not a" ); A is a letter
Serial.print (" hexadecimal digit\r" ); b is a letter
Serial.print (isxdigit( 'f' ) ? f is a" : "f is not & is not a letter
4 is not a letter
a"); According to isalnum:
A is a digit or a letter
}
8 is a digit or a letter
# is not a digit or a letter
void loop () { According to isxdigit:
F is a hexadecimal digit
J is not a hexadecimal digit
} 7 is a hexadecimal digit

$ is not a hexadecimal digit


f is a hexadecimal digit
Arduino - Math Library

The Arduino Math library (math.h) includes a number of useful mathematical functions for
manipulating floating-point numbers.
double double__x = 45.45 ;
double double__y = 30.20 ;

void setup() {
Serial.begin(9600);
Serial.print("cos num = ");
Serial.println (cos (double__x) ); // returns cosine of x
Serial.print("absolute value of num = ");
Serial.println (fabs (double__x) ); // absolute value of a float
Serial.print("floating point modulo = ");
Serial.println (fmod (double__x, double__y)); // floating point modulo
Serial.print("sine of num = ");
Serial.println (sin (double__x) ) ;// returns sine of x
Serial.print("square root of num : ");
Serial.println ( sqrt (double__x) );// returns square root of x
Serial.print("tangent of num : ");
Serial.println ( tan (double__x) ); // returns tangent of x
Serial.print("exponential value of num : ");
Serial.println ( exp (double__x) ); // function returns the exponential value of x.
Serial.print("cos num : ");
Serial.println (atan (double__x) ); // arc tangent of x
Serial.print("tangent of num : ");
Serial.println (atan2 (double__y, double__x) );// arc tangent of y/x cos num = 0.10
Serial.print("arc tangent of num : "); absolute value of num = 45.45
Serial.println (log (double__x) ) ; // natural logarithm of x floating point modulo =15.25
Serial.print("cos num : "); sine of num = 0.99
Serial.println ( log10 (double__x)); // logarithm of x to base 10. square root of num : 6.74
Serial.print("logarithm of num to base 10 : "); tangent of num : 9.67
Serial.println (pow (double__x, double__y) );// x to power of y exponential value of num : ovf
Serial.print("power of num : "); cos num : 1.55
Serial.println (square (double__x)); // square of x tangent of num : 0.59
} arc tangent of num : 3.82
cos num : 1.66
void loop() { logarithm of num to base 10 : inf
power of num : 2065.70
}
Arduino - Trigonometric Functions

double sin(double x); //returns sine of x radians


double cos(double y); //returns cosine of y radians
double tan(double x); //returns the tangent of x radians
double acos(double x); //returns A, the angle corresponding to cos (A) = x
double asin(double x); //returns A, the angle corresponding to sin (A) = x
double atan(double x); //returns A, the angle corresponding to tan (A) = x

Example
double sine = sin(2); // approximately 0.90929737091
double cosine = cos(2); // approximately -0.41614685058
double tangent = tan(2); // approximately -2.18503975868
Arduino - Pulse Width Modulation

Pulse Width Modulation or PWM is a common technique used to vary the width of the pulses in
a pulse-train. PWM has many applications such as controlling servos and speed controllers,
limiting the effective power of motors and LEDs.

Pulse width modulation is basically, a square wave with a varying high and low time. A basic
PWM signal is shown in the following figure.

There are various terms associated with PWM −


•On-Time − Duration of time signal is high.
•Off-Time − Duration of time signal is low.
•Period − It is represented as the sum of on-time and off-time of PWM signal.
•Duty Cycle − It is represented as the percentage of time signal that remains on during the
period of the PWM signal.
analogWrite() Function
• The analogWrite() function writes an analog value (PWM wave) to a pin. It can be used to light
a LED at varying brightness or drive a motor at various speeds.
• After a call of the analogWrite() function, the pin will generate a steady square wave of the
specified duty cycle until the next call to analogWrite() or a call to digitalRead() or digitalWrite()
on the same pin. The frequency of the PWM signal on most pins is approximately 490 Hz.
• On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3
and 11 on the Leonardo also run at 980 Hz.

The Arduino Due


supports analogWrite() on pins
2 through 13, and pins DAC0 and
DAC1. Unlike the PWM pins, DAC0
and DAC1 are Digital to Analog
converters, and act as true
analog outputs.
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
}
Arduino - Interrupts

Interrupts stop the current work of Arduino such that some other work can be done.

•Interrupts can come from various sources. In this case, we are


using a hardware interrupt that is triggered by a state change
on one of the digital pins.
•Most Arduino designs have two hardware interrupts (referred
to as "interrupt0" and "interrupt1") hard-wired to digital I/O
pins 2 and 3, respectively.
•The Arduino Mega has six hardware interrupts including the
additional interrupts ("interrupt2" through "interrupt5") on
pins 21, 20, 19, and 18.
•You can define a routine using a special function called as
Interrupt Service Routine (usually known as ISR).
•You can define the routine and specify conditions at the rising
edge, falling edge or both. At these specific conditions, the
interrupt would be serviced.
•It is possible to have that function executed automatically,
each time an event happens on an input pin.
Types of Interrupts
There are two types of interrupts −
•Hardware Interrupts − They occur in response to an external event, such as an external
interrupt pin going high or low.
•Software Interrupts − They occur in response to an instruction sent in software. The only
type of interrupt that the Arduino language supports is the attachInterrupt() function.

The following three constants are predefined as valid values −


•LOW to trigger the interrupt whenever the pin is low.
•CHANGE to trigger the interrupt whenever the pin changes value.
•FALLING whenever the pin goes from high to low.
int pin = 2; //define interrupt pin to 2
volatile int state = LOW; // To make sure variables shared between an ISR
//the main program are updated correctly,declare them as volatile.

void setup() {
pinMode(13, OUTPUT); //set pin 13 as output
attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);
//interrupt at pin 2 blink ISR when pin to change the value
}
void loop() {
digitalWrite(13, state); //pin 13 equal the state value
}

void blink() {
//ISR function
state = !state; //toggle the state when the interrupt occurs
}
Arduino - Communication

Hundreds of communication protocols have been defined to achieve this data exchange. Each
protocol can be categorized into one of the two categories: parallel or serial.

Parallel Communication
• Parallel connection between the Arduino and peripherals via input/output ports is the ideal
solution for shorter distances up to several meters.
• However, in other cases when it is necessary to establish communication between two devices
for longer distances it is not possible to use parallel connection.
• Parallel interfaces transfer multiple bits at the same time.
• They usually require buses of data - transmitting across eight, sixteen, or more wires. Data is
transferred in huge, crashing waves of 1s and 0s.
Serial Communication Modules
Today, most Arduino boards are built with several different systems for serial communication as
standard equipment.
Which of these systems are used depends on the following factors −

•How many devices the microcontroller has to exchange data with?


•How fast the data exchange has to be?
•What is the distance between these devices?
•Is it necessary to send and receive data simultaneously?

Types of Serial Communications


Serial communication can be further classified as −
•Synchronous − Devices that are synchronized use the same clock and their timing is in
synchronization with each other.
•Asynchronous − Devices that are asynchronous have their own clocks and are triggered by
the output of the previous state.
It is easy to find out if a device is synchronous or not. If the same clock is given to all
the connected devices, then they are synchronous. If there is no clock line, it is
asynchronous.
For example, UART (Universal Asynchronous Receiver Transmitter) module is
asynchronous.
The asynchronous serial protocol has a number of built-in rules. These rules are
nothing but mechanisms that help ensure robust and error-free data transfers. These
mechanisms, which we get for eschewing the external clock signal, are −

•Synchronization bits
•Data bits
•Parity bits
•Baud rate
Synchronization Bits
• The synchronization bits are two or three special bits transferred with each packet
of data. They are the start bit and the stop bit(s). True to their name, these bits
mark the beginning and the end of a packet respectively.
• There is always only one start bit, but the number of stop bits is configurable to
either one or two (though it is normally left at one).
• The start bit is always indicated by an idle data line going from 1 to 0, while the
stop bit(s) will transition back to the idle state by holding the line at 1.
Data Bits
The amount of data in each packet can be set to any size from 5 to 9 bits. Certainly, the
standard data size is your basic 8-bit byte, but other sizes have their uses. A 7-bit data packet
can be more efficient than 8, especially if you are just transferring 7-bit ASCII characters.

Parity Bits
The user can select whether there should be a parity bit or not, and if yes, whether the parity
should be odd or even. The parity bit is 0 if the number of 1s among the data bits is even. Odd
parity is just the opposite.

Baud Rate
The term baud rate is used to denote the number of bits transferred per second [bps]. Note that it
refers to bits, not bytes. It is usually required by the protocol that each byte is transferred along
with several control bits. It means that one byte in serial data stream may consist of 11 bits. For
example, if the baud rate is 300 bps then maximum 37 and minimum 27 bytes may be transferred
per second.
void setup() {
Serial.begin(9600); //set up serial library baud rate to 9600
Serial.println("hello world"); //print hello world
}

void loop() {

}
Arduino - Inter Integrated Circuit

Inter-integrated circuit (I2C) is a system for serial data exchange between the microcontrollers
and specialized integrated circuits of a new generation. It is used when the distance between
them is short (receiver and transmitter are usually on the same printed board). Connection is
established via two conductors. One is used for data transfer and the other is used for
synchronization (clock signal).

As seen in the following figure, one device is always a master. It performs addressing of one
slave chip before the communication starts. In this way, one microcontroller can communicate
with 112 different devices. Baud rate is usually 100 Kb/sec (standard mode) or 10 Kb/sec (slow
baud rate mode). Systems with the baud rate of 3.4 Mb/sec have recently appeared. The
distance between devices, which communicate over an I2C bus is limited to several meters.
Board I2C Pins
The I2C bus consists of two signals − SCL and SDA. SCL is the clock signal, and SDA
is the data signal. The current bus master always generates the clock signal. Some
slave devices may force the clock low at times to delay the master sending more
data (or to require more time to prepare data before the master attempts to clock it
out). This is known as clock stretching.

Following are the pins for different Arduino boards −

•Uno, Pro Mini A4 (SDA), A5 (SCL)


•Mega, Due 20 (SDA), 21 (SCL)
•Leonardo, Yun 2 (SDA), 3 (SCL)
Arduino - Blinking LED
Components Required
•1 × Breadboard
•1 × Arduino Uno R3
•1 × LED
•1 × 330 Resistor
•2 × Jumper
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
*/
// the setup function runs once when you press reset or power the board

void setup() { // initialize digital pin 13 as an output.


pinMode(2, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Arduino - Fading LED

This example demonstrates the use of the analogWrite() function in fading an LED off.
AnalogWrite uses pulse width modulation (PWM), turning a digital pin on and off very quickly with
different ratios between on and off, to create a fading effect.
Components Required
•1 × Breadboard
•1 × Arduino Uno R3
•1 × LED
•1 × 330 Resistor
•2 × Jumper
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:

void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}

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

void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(300);
}

You might also like