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

Es Arduino 6

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

Es Arduino 6

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

Lecture 6

 Digital and Analog interfacing.


 Serial port Programming.
 PWM Programming.
 Interfacing Devices; Sensors,
Intro to Arduino
Displays, Motors, and Relays to
Arduino.

Material designed by Linz Craig, Nick Poole, Prashanta Aryal,


.
Theo Simpson, Tai Johnson, and Eli Santistevan
USB
PWR IN (to Computer)

RESET

SCL\SDA
(I2C Bus)

POWER
5V / 3.3V / GND
Digital I\O
PWM(3, 5, 6, 9, 10, 11)

Analog
INPUTS

2
USB
PWR IN (to Computer)

RESET

SCL\SDA
(I2C Bus)

POWER
5V / 3.3V / GND
Digital I\O
PWM(3, 5, 6, 9, 10, 11)

Analog
INPUTS

3
Components
Name Image Type Function Notes
Push Button Digital Input Switch - Closes Polarized, needs
or opens circuit resistor
Trim Analog Input Variable resistor Also called a
Trimpot.
potentiometer
Photoresistor Analog Input Light Dependent Resistance varies
Resistor (LDR) with light.
Relay Digital Output Switch driven by Used to control
a small signal larger voltages
Temp Sensor Analog Input Temp Dependent
Resistor
Flex Sensor Analog Input Variable resistor

Soft Trimpot Analog Input Variable resistor Careful of shorts

RGB LED Dig & Analog 16,777,216 Ooh... So pretty.


Output different colors

4
Components

5
Components

6
SIK Components

7
8
Electronics Basic Concept

 Ohms Law
 Voltage
 Current
 Resistance
 Using a Multi-meter

9
Ohm’s Law

Voltage Current Resistance


V I R
• Defined as • The rate of
the amount charge flow
of potential in a circuit.
energy in a • Units: Amperes
circuit. (A)
• Units: Volts (V)

10
Current Flow Analogy

High Current Low Current

11
Voltage Analogy

Water
Tower
Water
Tower

V
V

More Energy == Higher Voltage Less Energy == Lower Voltage

12
Resistance Analogy

Water Water
Tower Tower

Big Pipe == Lower Resistance Small Pipe == Higher Resistance

13
Continuity – Is it a Circuit?
 The word “circuit” is derived from the circle. An
Electrical Circuit must have a continuous LOOP from
Power (Vcc) to Ground (GND).

 Continuity is important to make portions of circuits


are connect. Continuity is the simplest and possibly
the most important setting on your multi-meter.
Sometimes we call this “ringing out” a circuit.

14
Measuring Electricity – Voltage

 Voltage is a measure of potential electrical


energy. A voltage is also called a potential
difference – it is measured between two
points in a circuit – across a device.

15
Measuring Electricity -- Current

 Current is the measure of the rate of charge flow. For


Electrical Engineers – we consider this to be the
movement of electrons.
 In order to measure this – you must break the circuit or
insert the meter in-line (series).

16
Measuring Electricity -- Resistance

 Resistance is the measure of how much opposition to


current flow is in a circuit.
 Components should be removed entirely from the
circuit to measure resistance. Note the settings on
the multi-meter. Make sure that you are set for the
appropriate range.
Resistance
settings

17
What’s a Breadboard?

18
Solderless Breadboard

Each row (horiz.) of 5


holes are connected.

Vertical columns –
called power bus are
connected vertically

19
Using the Breadboard to built a
simple circuit

Use the breadboard to


wire up a single LED
with a 330 Ohm
Resistor (Orange-
Orange-Brown).

Note: the longer leg on the


LED is the positive leg and
the shorter leg is the
negative

20
Concepts: INPUT vs. OUTPUT

Inputs is a signal / information Output is any signal exiting the


going into the board. board.

Examples: Buttons Switches,


Light Sensors, Flex Sensors,
Humidity Sensors, Temperature
Sensors…

21
Concepts: Analog vs. Digital
 Microcontrollers are digital devices – ON or
OFF. Also called – discrete.

 analog signals are anything that can be a full


range of values. What are some examples?
More on this later…

5V 5V

0V 0V

22
Let’s get to coding…

Project #1 – Blink
“Hello World” of Physical Computing

Psuedo-code – how should this work?

Turn
Turn Rinse &
Wait LED Wait
LED ON Repeat
OFF

23
Comments, Comments,
Comments
 Comments are for you – the programmer and your
friends…or anyone else human that might read your
code.

// this is for single line comments


// it’s good to put a description at the
top and before anything ‘tricky’
/* this is for multi-line comments
Like this…
And this….
*/
24
comments

25
Three commands to know…
pinMode(pin, INPUT/OUTPUT);
ex: pinMode(13, OUTPUT);

digitalWrite(pin, HIGH/LOW);
ex: digitalWrite(13, HIGH);

delay(time_ms);
ex: delay(2500); // delay of 2.5 sec.

// NOTE: -> commands are CASE-sensitive

26
Project #1: Wiring Diagram

Move the green


wire from the
power bus to pin
13 (or any other
Digital I/O pin on
the Arduino board.

27
Add an External LED to pin 13

• File > Examples > Digital > Blink


• LED’s have polarity
– Negative indicated by flat side of the housing
and a short leg

28
LED
int ledPin = 13; // LED connected to digital pin 13

// The setup() method runs once, when the sketch starts

void setup() {
// initialize the digital pin as an output:
pinMode(ledPin, OUTPUT);
}

// the loop() method runs over and over again,


// as long as the Arduino has power

void loop()
{
digitalWrite(ledPin, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(ledPin, LOW); // set the LED off
delay(1000); // wait for a second
}
29
A few simple challenges
Let’s make LED#13 blink!
Challenge 1a – blink with a 200 ms second
interval.

Challenge 1b – blink to mimic a heartbeat

Challenge 1c – find the fastest blink that the


human eye can still detect…
1 ms delay? 2 ms delay? 3 ms delay???

30
Try adding other LEDs

31
Programming Concepts: Variables

Variable Scope

Global
---
Function-level

32
Fading in and Fading Out
(Analog or Digital?)
 A few pins on the Arduino allow for us to
modify the output to mimic an analog
signal.

 This is done by a technique called:


Pulse Width Modulation (PWM)

33
Concepts: Analog vs. Digital

 To create an analog signal, the microcontroller


uses a technique called PWM. By varying the
duty cycle, we can mimic an “average” analog
voltage.

Pulse Width Modulation (PWM)

34
Project #2 – Fading
Introducing a new command…

analogWrite(pin, val);

pin – refers to the OUTPUT pin


(limited to pins 3, 5, 6, 9, 10, 11.)
– denoted by a ~ symbol

val – 8 bit value (0 – 255).


0 => 0V | 255 => 5V

35
Move one of your LED pins over to
Pin 9
In Arduino, open up:
File  Examples  01.Basics  Fade

36
Fade - Code Review

37
Fade - Code Review

38
Project# 2 -- Fading

 Challenge 2a – Change the rate of the


fading in and out. There are at least two
different ways to do this – can you figure
them out?

 Challenge 2b – Use 2 (or more) LEDs –


so that one fades in as the other one fades
out.

39
R G B
Color Mixing
Tri-color LED

 In the SIK, this is a standard –


Common Cathode LED

 This means the negative side of


the LED is all tied to Ground.

40
Project 3 – RGB LED

Note: The longest


leg of the RGB
LED is the
Common
Cathode. This
goes to GND.

Use pins 5, 6, & 9

41
How many unique colors can you create?

Use Colorpicker.com or
experiment on your
own.
Pick out a few colors that
you want to try re-
creating for a lamp or
lighting display...
Play around with this with
the analogWrite()
command.
42
RGB LED Color Mixing

int redPin = 5;
int greenPin = 6;
int bluePin = 9;

void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}

43
RGB LED Color Mixing

void loop()
{
analogWrite(redPin, 255);
analogWrite (greenPin, 255);
analogWrite (bluePin, 255);
}

44
Project: Mood Lamp / Light Sculpture

45
Driving Motors or other High Current
Loads

NPN Transistor (Common Emitter “Amplifier” Circuit)

to Digital
Pin 9

46
Input

Input is any signal entering an electrical system.


• Both digital and analog sensors are forms of input
• Input can also take many other forms: Keyboards, a
mouse, infrared sensors, biometric sensors, or just
plain voltage from a circuit

47
Project #4 – Digital Input

In Arduino, open up:


File  Examples  02.Digital  Button

48
Button

• Pushbuttons or
switches connect
two points in a
circuit when you
press them. This
example turns on
the built-in LED on
pin 13 when you
press the button.

49
Digital Sensors (a.k.a. Switches)
Pull-up Resistor (circuit)

to Digital Pin 2

50
Digital Sensors (a.k.a. Switches)
Add an indicator LED to Pin 13
This is just like our
1st circuit!

51
Digital Input

 Connect digital input to your Arduino using Pins # 0 – 13


(Although pins # 0 & 1 are also used for programming)

 Digital Input needs a pinMode command:


pinMode (pinNumber, INPUT);
Make sure to use ALL CAPS for INPUT

 To get a digital reading:


int buttonState = digitalRead (pinNumber);

 Digital Input values are only HIGH (On) or LOW (Off)


52
Button

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


int ledPin = 13; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}

void loop(){
buttonState = digitalRead(buttonPin); // read the state of the pushbutton
value:

if (buttonState == HIGH) { // check if the pushbutton is pressed. If it is, the


buttonState is HIGH:
digitalWrite(ledPin, HIGH); // turn LED on:
}
else {
digitalWrite(ledPin, LOW); // turn LED off:
}
}
53
Button

• The problem with the last program is that the


switch has to remain pressed in order for the
LED to turn on
• We want the LED to change state when we
press the button and to stay in the new state
when the button is released

54
Button
int buttonPin = 2; // the pin that the pushbutton is attached to
int ledPin = 13; // the pin that the LED is attached to
int buttonState = 0; // current state of the button
int lastLEDState = 0; // previous state of the button

void setup() {
pinMode(buttonPin, INPUT); // initialize the button pin as a input:
pinMode(ledPin, OUTPUT); // initialize the LED as an output:
}

void loop() {
buttonState = digitalRead(buttonPin); // read the pushbutton input pin:

if (buttonState == HIGH) { // Determine if button State is HIGH


if (lastLEDState == HIGH) { // if the current state is HIGH then turn LED off
digitalWrite(ledPin, LOW);
lastLEDState = LOW;
}
else {// if the current state is LOW then turn LED on
digitalWrite(ledPin, HIGH);
lastLEDState = HIGH;
}
while(buttonState == HIGH){
buttonState = digitalRead(buttonPin); // read the pushbutton input pin:
};
delay(250);
}
} 55
Digital Sensors

 Digital sensors are more straight forward than Analog

 No matter what the sensor there are only two


settings: On and Off

 Signal is always either HIGH (On) or LOW (Off)

 Voltage signal for HIGH will be a little less than 5V on


your Uno

 Voltage signal for LOW will be 0V on most systems

56
Digital Input

void loop()
{
int buttonState = digitalRead(5);
if(buttonState == LOW)
{ // do something DIG
INPUT
}
else
{ // do something else
}
}
57
Analog Sensors
3 Pin Potentiometer = var. resistor (circuit)
a.k.a. Voltage Divider Circuit

wiper

fixed
ends 1.0 V 1.0 V

58
Analog Sensors
2 Pin Analog Sensors = var. resistor

Take two sensors -- Use


the Serial Monitor and find
the range of input values
you get for each sensor.

MaxAnalogRead = _________

MinAnalogRead = _________

59
Analog Sensors

Examples:
Sensors Variables
Mic soundVolume
Photoresistor lightLevel
Potentiometer dialPosition
Temp Sensor temperature
Flex Sensor bend
Accelerometer tilt/acceleration

60
Ohms Law… (just the basics)
Actually, this is the “voltage divider”

61
analogRead()

Arduino uses a 10-bit A/D Converter:


• this means that you get input values from
0 to 1023
• 0V0
• 5 V  1023
Ex:
int sensorValue = analogRead(A0);

62
Reading analog inputs and scaling
const int potPin = 0; // select the input pin for the potentiometer

void loop()
{
int val; // The value coming from the sensor
int percent; // The mapped value
val = analogRead(potPin); // read the voltage on the pot (val ranges from 0 to 1023)
percent = map(val,0,1023,0,100); // percent will range from 0 to 100.
}

63
Measuring Temperature

const int inPin = 0; // analog pin


void loop()
{
int value = analogRead(inPin);
float millivolts = (value / 1024.0) * 3300; //3.3V analog input
float celsius = millivolts / 10; // sensor output is 10mV per
degree Celsius
delay(1000); // wait for one second
}

64
Using PIR motion sensors

65
Using PIR motion sensors
const int ledPin = 7; // pin for the LED
const int inputPin = 2; // input pin (for the PIR sensor)
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
int val = digitalRead(inputPin); // read input value
if (val == HIGH) // check if the input is HIGH
{
digitalWrite(ledPin, HIGH); // turn LED on if motion detected
delay(500);
digitalWrite(ledPin, LOW); // turn LED off
}
} 66
Using ultrasonic sensors

 The “ping” sound pulse is generated when the pingPin level


goes HIGH for two microseconds.

 The sensor will then generate a pulse that terminates when


the sound returns.

 The width of the pulse is proportional to the distance the


sound traveled

 The speed of sound is 340 meters per second, which is 29


microseconds per centimeter. The formula for the distance

 of the round trip is: RoundTrip = microseconds / 29

67
Using ultrasonic sensors
const int pingPin = 5;
const int ledPin = 7; // pin connected to LED
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop()
{
int cm = ping(pingPin) ;
Serial.println(cm);
digitalWrite(ledPin, HIGH);
delay(cm * 10 ); // each centimeter adds 10 milliseconds delay
digitalWrite(ledPin, LOW);
delay( cm * 10);
} 68
Using ultrasonic sensors
int ping(int pingPin)
{
long duration, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
return cm ;
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
69
Digital Output-Sound-Piezo

 A Piezo is an electronic piece that converts electricity


energy to sound. It is a digital output device. You can
make white noise or even exact musical notes (
frequencies for musical notes) based on the duration
that you iterate between HIGH and LOW signals.

 A Piezo is a directional piece, meaning that it has a


positive and negative pole. The positive pole should
be connected to the digital output pin that you allocate
to control the piezo and the negative pole should be
connected to Ground pin
70
Digital Output-Sound-Piezo

71
Digital Output-Sound-Piezo

//connect piezo to pin 13 and ground


int freqs[] = {
1915, 1700, 1519, 1432, 1275, 1136, 1014, 956};
//string tones[] = {"do", "re", "mi", "fa","sol"," la", "si", "do"};
void setup(){
pinMode(13,OUTPUT);
}
void loop(){
for(int i=0;i<8;i++){//iterating through notes
for(int j=0;j<1000;j++){//the time span that each note is being played
digitalWrite(13,HIGH);
delayMicroseconds(freqs[i]);
digitalWrite(13,LOW);
delayMicroseconds(freqs[i]);
}
} 72
}
Digital Output-Sound-Piezo-Playing a melody

73
Digital Output-Sound-Piezo-Playing a melody
//connect piezo to pin 13 and ground
void playNote(int note)
{
for(int j=0;j<60;j++){//the time span that each note is being played
digitalWrite(13,HIGH);
delayMicroseconds(note);
digitalWrite(13,LOW);
delayMicroseconds(note);
}
delay(60);
}
int pause=200;
int freqs[] = {
1915, 1700, 1519, 1432, 1275, 1136, 1014, 956};
//string tones[] = {"do", "re", "mi", "fa","sol"," la", "si", "do"};
// i={0 1 2 3 4 5 6 7
//mi mi mi - mi mi mi - mi sol do re mi - - - fa fa fa fa fa mi mi mi mi re re mi re - sol - mi mi mi - mi mi mi - mi sol do re mi -- fa fa fa fa fa mi mi mi sol sol fa re do - - -
void setup(){
pinMode(13,OUTPUT);
}
void loop(){
playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]); delay(pause);
playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]); delay(pause);
playNote(freqs[2]); playNote(freqs[4]); playNote(freqs[0]); playNote(freqs[1]);
playNote(freqs[2]); delay(pause); delay(pause); delay(pause);
playNote(freqs[3]); playNote(freqs[3]); playNote(freqs[3]); playNote(freqs[3]);
playNote(freqs[3]); playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]);
playNote(freqs[2]); playNote(freqs[1]); playNote(freqs[1]); playNote(freqs[2]);
playNote(freqs[1]); delay(pause); playNote(freqs[4]); delay(pause);
playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]); delay(pause);
playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]); delay(pause);
playNote(freqs[2]); playNote(freqs[4]); playNote(freqs[0]); playNote(freqs[1]);
playNote(freqs[2]); delay(pause); delay(pause); delay(pause);
playNote(freqs[3]); playNote(freqs[3]); playNote(freqs[3]); playNote(freqs[3]);
playNote(freqs[3]); playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]);
playNote(freqs[4]); playNote(freqs[4]); playNote(freqs[3]); playNote(freqs[3]);
playNote(freqs[0]); delay(pause); delay(pause); delay(pause);
}
74
Same Signal Multiple Interpretations

In the same setting if you connect an LED parallel to Piezo,


you can see how the same signal can be interpreted
differently using a different output device that accept the same
type of signals(in this case digital signal) 75
DigitalOutput-Motion-Servo Motor

Servo Motors are electronic devices that convert digital


signal to rotational movement. There are two sorts of servo
motors: Standard servos that their rotation is limited to
maximum of 180 degrees in each direction and Continuous
Rotation Servos that can provide rotation unlimitedly in both
directions 76
DigitalOutput-Motion-Servo Motor

A servo motor is a motor that pulses at a certain rate


moving its gear at a certain angle. It has three connections:
the black is ground, the red is connected to 5V, and the
white (yellow wire here) is set to the digital pin.

Ground

V5

Digital Pin

77
Standard Servo Rotation to Exact Angel

78
Standard Servo Rotation to Exact Angel
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
myservo.attach(9);
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
myservo.detach(); //Detach the servo if you are not controling it for a while
delay(2000);
} 79
Controlling Standard Servo with User Input

80
Controlling Standard Servo with User Input
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
int angleValue=0;
int serialNumber=0;
void setup()
{
Serial.begin(9600);
myservo.attach(9);
}
void loop()
{
int value=Serial.read();
Serial.println(value);
if(value!=-1 && value!=10){
serialNumber=serialNumber*10+(value-48);
}
if(value==10){
myservo.attach(9);
angleValue=serialNumber%180;
myservo.write(angleValue); // tell servo to go to position in variable 'pos'
Serial.print("Number Recieved from Serial Port:");
Serial.println(serialNumber);
serialNumber=0;
delay(250);
}
myservo.detach(); 81
}
Controlling Servo with User Input

82
DigitalOutput - Continuous Rotation
As opposed to standard Servo that its rotation is limited to
180 degrees both ways, a continuous rotation servo can
keep rotating unlimitedly-again both ways- based on the
frequency that is pulsed out to it. There is a specific
frequency at which the Servo motor should be static and
beyond and before which the servo will change in its rotation
direction.
Ground

V5

Digital Pin

83
Digital Output - Continuous Rotation-
Adjustment
As opposed to standard Servo that its rotation is limited to 180
degrees both ways, a continuous rotation servo can keep
rotating unlimitedly-again both ways- based on the frequency that
is pulsed out to it. There is a specific frequency at which the
Servo motor should be static and beyond and before which the
servo will change in its rotation direction.
There is a pin on the servo motor that enables us to adjust the
servo for its static frequency.

84
Digital Output - Continuous Rotation-
Adjustment

Upload the following code to the


board and while the servo is
connected, try to adjust the pin
until the servo motor is static.
Once the servo is adjusted to this
code any pulse grater than 1500
will result in rotation in one
direction while any pulse less void setup()
than 1500 will result in rotation in {
pinMode(5,OUTPUT);
the other direction }
void loop()
{
for (int i = 0; i <= 200; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1500); // 1.5ms This is the frequency at which the servo motor should be static
digitalWrite(5,LOW);
delay(20); // 20ms
}
}

85
Digital Output - Continuous Rotation-Direction
Change
Once the servo is adjusted to this code any pulse grater than
1500 will result in rotation in one direction while any pulse
less than 1500 will result in rotation in the other direction

86
void setup()
{
pinMode(5,OUTPUT);
Digital Output
}
void loop()
{
Continuous Rotation
//Rotating in One direction
for (int i = 0; i <= 200; i++)
{
Direction Change
digitalWrite(5,HIGH);

delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20); // 20ms
} Once the servo is adjusted to this code any
//Stop
for (int i = 0; i <= 200; i++) pulse grater than 1500 will result in rotation
{
digitalWrite(5,HIGH); in one direction while any pulse less than
delayMicroseconds(1500); 1500 will result in rotation in the other
digitalWrite(5,LOW);
delay(20); // 20ms direction
}
//Rotating in the other direction
for (int i = 0; i <= 200; i++)
{
digitalWrite(5,HIGH);

delayMicroseconds(1200);
digitalWrite(5,LOW);
delay(20); // 20ms
}
//Stop
for (int i = 0; i <= 200; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1500);
digitalWrite(5,LOW);
delay(20); // 20ms
} 87
}
void setup()
{
pinMode(5,OUTPUT);
}
void loop()
{
//Continious Rotation
for (int i = 0; i <= 20; i++)
Digital Output
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);
Continuous Rotation
delay(1);
}
//Rotating with delayed steps
for (int i = 0; i <= 20; i++)
Delayed Steps
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(100);
}
//More Delay
for (int i = 0; i <= 20; i++)
Playing with delay() gives us pauses between rotation
{
digitalWrite(5,HIGH); steps
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(200);
}
//More Delay
for (int i = 0; i <= 20; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(400);
}
//More Delay
for (int i = 0; i <= 20; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(800);
}
//More Delay
for (int i = 0; i <= 20; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(1800);
} 88
}
Digital Output - Continuous Rotation-
Controlling Rotation Angle

void setup() Playing with the number of steps in the for loop gives us
{
pinMode(5,OUTPUT);
}
variations in the span /Angle of the rotation
void loop()
{

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


{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20);
}
delay(1000);

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


{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20);
}
delay(1000);

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


{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20);
}
delay(1000);

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


{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20);
}
delay(1000);
}
89
Digital Output – Wind –Controlling a Fan

Controlling a Fan is as easy as sending a HIGH or LOW Signal to the Pin that the fan
is connected to.

// Connect the fan to Pin 13 and Ground


void setup(){
pinMode(13, OUTPUT); // Specify Arduino Pin number
and output/input mode
}
void loop(){
digitalWrite(13, HIGH); // Turn on Pin 13 sending a
HIGH Signal
delay(1000); // Wait for one second
digitalWrite(13, LOW); // Turn off Pin 13 sending a
LOW Signal
delay(3000); // Wait for Three second
}

90
Digital Output – Rotation –Controlling a DC
Motor
// Connect to Pin 13 and Ground
void setup(){
pinMode(13, OUTPUT); // Specify Arduino Pin number
and output/input mode Code for Rotation/No Rotation
}
void loop(){
digitalWrite(13, HIGH); // Turn on Pin 13 sending a
HIGH Signal
delay(1000); // Wait for one second
digitalWrite(13, LOW); // Turn off Pin 13 sending a
LOW Signal
delay(3000); // Wait for Three second
}

// Connect to Pin 13 and 12


void setup(){
pinMode(13, OUTPUT); // Specify Arduino Pin number
and output/input mode
pinMode(12, OUTPUT);
}
void loop(){
digitalWrite(13, HIGH); // Turn on Pin 13 sending a
HIGH Signal
digitalWrite(12, LOW); //Make Pin 12 a Ground
delay(1000); // Wait for one second
digitalWrite(13, LOW); // Make Pin 13 a Ground Code for CW and CCW Rotation
digitalWrite(12, HIGH); // Turn on Pin 12 sending a
HIGH Signal
delay(3000); // Wait for Three second
}
91
Arduino- Digital Output–Rotation–
Stepper Motor
2

3
4
5

Stepper motors translate digital switching sequences into motion. They are used in a variety
of applications requiring precise motions under computer control.
Unlike ordinary dc motors, which spin freely when power is applied,steppers require that their
power source be continuously pulsed in specific patterns. These patterns, or step
sequences, determine the speed and direction of a stepper’s motion.
For each pulse or step input, the stepper motor rotates a fixed angular increment; typically
1.8 or 7.5 degrees.
Steppers are driven by the interaction (attraction and repulsion) of magnetic fields. The
driving magnetic field “rotates” as strategically placed coils are switched on and off. This
pushes and pulls at permanent magnets arranged around the edge of a rotor that drives92the
output shaft.
Stepper Motor

When the on-off pattern of the magnetic fields is in the proper sequence, the stepper turns
(when it’s not, the stepper sits and quivers).

The most common stepper is the four-coil unipolar variety. These are called unipolar because
they require only that their coils be driven on and off. Bipolar steppers require that the polarity
of power to the coils be reversed.

The normal stepping sequence for four-coil unipolar steppers appears in the figure. If you run
the stepping sequence in the figure forward, the stepper rotates clockwise; run it backward,
and the stepper rotates counterclockwise.

The motor’s speed depends on how fast the controller runs through the step sequence. At any
time the controller can stop in mid sequence.

If it leaves power to any pair of energized coils on, the motor is locked in place by their
magnetic fields. This points out another stepper motor benefit: built-in brakes. 93
Stepper Motor

94
void setup(){
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
Stepper Moto
pinMode(5,OUTPUT);
}
void loop(){
// Pause between the types that determines the speed
Direction and Speed
int stepperSpeed=200;// Change to change speed
int dir=1;// change to -1 to change direction
if (dir==1){ //Running Clockwise
digitalWrite(2,HIGH);//Step 1
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,HIGH);//Step 2
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,LOW);//Step 3
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,LOW);//Step 4
digitalWrite(3,HIGH);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(stepperSpeed);// Pause between the types that determines the speed
}
if (dir==-1){ //Running CounterClockwise
digitalWrite(2,LOW);//Step 4
digitalWrite(3,HIGH);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,LOW);//Step 3
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,HIGH);//Step 2
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,HIGH);//Step1
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(stepperSpeed);// Pause between the types that determines the speed
} 95
}
Vibration Motor
A vibration motor! This itty-bitty, shaftless vibratory motor is
perfect for non-audible indicators. Use in any number of
applications to indicate to the wearer when a status has
changed. All moving parts are protected within the housing.
With a 2-3.6V operating range, these units shake crazily at
3V. Once anchored to a PCB or within a pocket, the unit
vibrates softly but noticeably. This high quality unit comes
with a 3M adhesive backing and reinforced connection wires.

96
Digital Output – Controling any Electrical
Device with any power needs using a relay

Externally Powered Device

3v-220v
External Power
Externally Powered Device

// Connect to Pin 13 and Ground


void setup(){
pinMode(13, OUTPUT); // Specify Arduino Pin number and
output/input mode
}
void loop(){
digitalWrite(13, HIGH); // Turn on Pin 13 sending a HIGH Signal
delay(1000); // Wait for one second
digitalWrite(13, LOW); // Turn off Pin 13 sending a LOW Signal
delay(3000); // Wait for Three second
}

Control Pin
97
Using Serial Communication

Method used to transfer data between two devices.

Data passes between the computer and Arduino


through the USB cable. Data is transmitted as zeros
(‘0’) and ones (‘1’) sequentially.

Arduino dedicates Digital I/O pin # 0 to


receiving and Digital I/O pin #1 to transmit.

98
Serial Monitor & analogRead()

Initializes the Serial


Communication

9600 baud data rate


prints data to serial bus99
Serial Monitor & analogRead()

Opens up a
Serial Terminal
Window

10
Additional Serial Communication
Sending a Message

void loop ( )
{
Serial.print(“Hands on “) ;
Serial.print(“Learning ”) ;
Serial.println(“is Fun!!!”) ;

}
10
10
Serial Communication:
Serial Debugging

void loop()
{
int xVar = 10;
Serial.print ( “Variable xVar is “ ) ;
Serial.println ( xVar ) ;
}

10
Serial Communication:
Serial Troubleshooting

void loop ( )
{
Serial.print (“Digital pin 9: “);
Serial.println (digitalRead(9));
}

10
Serial Communication

• Compiling turns your program into


binary data (ones and zeros)
• Uploading sends the bits through
USB cable to the Arduino
• The two LEDs near the USB
connector blink when data is
transmitted
• RX blinks when the Arduino is
receiving data
• TX blinks when the Arduino is
transmitting data 105
Some Commands

• Serial.begin()
- e.g., Serial.begin(9600)
• Serial.print() or Serial.println()
- e.g., Serial.print(value)
• Serial.read()
• Serial.available()
• Serial.write()
• Serial.parseInt()

106
Serial-to-USB chip---what does it do?

The LilyPad and Fio Arduino require an external USB to TTY connector, such as an FTDI
“cable”.
In the Arduino Leonardo a single microcontroller runs the Arduino programs and handles
the USB connection.

107
Two different communication protocols

Serial (TTL):

Image from http://www.fiz-ix.com/2013/02/introduction-to-arduino-serial-communication/

108
USB Protocol

Image from http://en.wikipedia.org/wiki/USB

109

You might also like