0% found this document useful (0 votes)
4 views18 pages

Arduino Notes

The document serves as an introduction to Arduino programming, covering basic concepts such as blinking LEDs, programming structures, and analog inputs. It explains the use of commands like pinMode, digitalWrite, and delay, as well as programming structures like if statements, while loops, and for loops. Additionally, it discusses the use of analog devices like potentiometers and photoresistors, and introduces servo motors for precise control.

Uploaded by

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

Arduino Notes

The document serves as an introduction to Arduino programming, covering basic concepts such as blinking LEDs, programming structures, and analog inputs. It explains the use of commands like pinMode, digitalWrite, and delay, as well as programming structures like if statements, while loops, and for loops. Additionally, it discusses the use of analog devices like potentiometers and photoresistors, and introduces servo motors for precise control.

Uploaded by

mostafallam9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Intro to Arduino

1-Blinking LED’s with Arduino


Objective: To make LED’s blink on a circuit board using the Arduino micro-controller.

1.1 Getting Started with Arduino

The Arduino Uno board is a micro-controller. A micro-controller is an integrated circuit that contains a small
computer with a processor, memory, and input/output pins.

The Arduino micro-controller works with a computer software package of the same name(through the USB
cable). A program in Arduino is called a “Sketch”. Each sketch contains:
• void setup () { } executes when the program starts.
• void loop () { } executes continuously while the Arduino has power.

In the void setup part of the code, all pins are defined as inputs and outputs. Other tasks are done in the
void setup, but for now all we need to worry about is setting pins as outputs.

The commands you want to execute in the circuit go in void loop. These commands will loop continuously
forever until you disconnect power. Unlike other languages where you specify a loop if needed, every program
in Arduino will have a loop.

1.2 Blinking an LED

Completing a task with Arduino with Arduino is a 2 step process: wiring the circuit and writing the script. To
wire an LED, it must be connected to one of digital pin, which are the 13 labeled DIGITAL. Digital outputs can
also be wired to the ANALOG IN pins, but analog inputs cannot be wired to the DIGITAL pins. The purpose of
the ANALOG pins will be covered in a later lesson. Ideally, current should flow from the digital output pin,
through the LED and a resistor and then to ground.

When wiring an LED, always make sure you include a resistor in series with the LED and that current
flows from the long leg to the short leg.

Programming a blinking LED involves 3 new commands. In general, the first word in an Arduino code is all
lower case and the first character of each additional word is upper case(with no spaces). The new commands
are:

• pinMode(pin#,input/output) – This set a pin as an input or output. For example, if we want to set an
LED connected to pin 9 as an output, we would type pinMode(9,OUTPUT). INPUT and OUTPUT are
always capitalized.
*If you are blinking an LED, the LED is always an output, though Arduino can actually read an LED as
a digital input to determine if it is on or off.
• digitalWrite(pin#,state) – Set a pin to on or off, or HIGH or LOW. For example, to turn the
output on pin 9 to high, the command would be digitalWrite(9,HIGH). Again, HIGH and LOW must be
capitalized. You can also use 1 for HIGH or 0 for LOW instead.
• delay(time) – Tells the program to wait before executing further commands. The input for time is in
milliseconds. If you want to wait 3 seconds, the command would be delay(3000).
Semicolons
Semicolons at the end of a line are not optional in Arduino. Every line of code must end in a semicolon! A
single line not ending with a semicolon will cause the program not to run.

Comments
Comments in Arduino work similar to MATLAB, except in Arduion they start with ‘//’ instead of ‘%’. Any text
after a ‘//’ on a line will not have an effect on the script running.

Example A: Make an LED blink on and off. This task is the “Hello World” of Arduino.

The wiring for this circuit is shown to the right. We are using pin 13.
The schematic would be:

As shown by the circuit flawlessly created in Microsoft paint, the current flows from pin 13, through the
resistor, through the LED, and then to ground. Whether the resistor or LED come first in the circuit is irrelevant,
as the circuit is a continuous loop.

For a delay of one second, the code would be

void setup(){
pinMode(13,OUTPUT); //set pin 13 to output
}

void loop(){
digitalWrite(13,HIGH); //turn LED on
delay(1000); //wait 1 second
digitalWrite(13,LOW); //turn LED off
delay(1000); //wait 1 second
}

When the void loop starts for the code above, the LED immediately turns on. While it’s on, the circuit does
nothing for 1 second, since we told it to delay for 1000 ms. After it turns off and waits an additional second. At
the end of the delay, it goes back to the top of the loop and turns back on.
Example B: Modify the sketch above to make the LED above blink by being on for 2 seconds and off for 1
second.

void setup(){
pinMode(13,OUTPUT); //set pin 13 to output
}

void loop(){
digitalWrite(13,HIGH); //turn LED on
delay(2000); //wait 1 second
digitalWrite(13,LOW); //turn LED off
delay(1000); //wait 1 second
}

Example C: Create an Arduino program with 2 LED’s. The LED’s should take turns being on in 1 second
intervals. Draw the schematic for the circuit and write out the program.

void setup(){
pinMode(13,OUTPUT); //set pin 13 to output
pinMode(12,OUTPUT); //set pin 12 to output
}

void loop(){
digitalWrite(12,HIGH); //turn LED 12 on
digitalWrite(13,LOW); //13 will be off by default, but this will turn it
//off when looping
delay(1000); //wait 1 second
digitalWrite(12,LOW); //turn LED off
digitalWrite(13,HIGH);
delay(1000); //wait 1 second
}
Intro to Arduino
2 – Programming in Arduino
Objective: To program circuits using the Arduino micro-controller.

2.1 Selection Structures in Arduino

➢ Like in other programs, an if structure will execute a segment of code while a certain condition is met.
The set-up for an if structure in Arduino is:

if( logical test ) {


//code to run
}

➢ The logical operators in Arduino are as follows:

• == equal to • != not equal to • < less than

• > greater than • >= greater or equal to • <= less or equal to

➢ An if statement in Arduino can also have an else clause if the condition is not met. Remember that
else itself does not have a logical test. However, an if structure can follow else. Arduino does not
have a dedicated “elseif” command. An example of a full if structure with an else if and an
else would be:
if(power>9000){
//do a thing}
else if (power == 9000){
// do another thing}
else {
//do something else}

Example A: Suppose a single LED is connected to pin 13. Write a program to make the LED blink faster and
faster before resetting.
2.2 Digital Input

➢ A pushbutton is an input to Arduino, which means Arduino will sense if it is on or off rather than tell it
to turn on or off. Since the push button has 2 modes, “pressed” or “not pressed”, the buttons are digital
inputs.
➢ To set a push button as a input:
pinMode(pinwithbutton, INPUT)
➢ When a button is set as input, we need to define the default state of the button as “high” or “low”.
Whenever the button is pressed by the user, the button will take on the opposite state of whatever we
initially set it as. To set input HIGH or LOW:
digitalWrite(pinwithbutton, HIGH) or digitalWrite(pinwithbutton, LOW)
➢ If an input is set to HIGH, a 20k Ω interal resistor connects the element to ground from a 5V source. If
the input is LOW, it is simply off.
➢ if structures can be used with pushbuttons to control circuits depending on the button input or output.

Example B: Create the circuit shown. Program the LED to turn on


when the push button is pressed. Draw the circuit schematic and
write out the required code.
2.3 Do and Do While Loops

➢ A ‘while’ loop is a loop that will execute over and over again continuously while a certain condition is
met. The syntax for a ‘while’ statement in Arduino code is:

while(condition){
//do stuff
}

➢ The conditions for a ‘while’ loop work the same as for ‘if’ statements in the previous section.
Remember to use ‘==’ and not ‘=’ when defining a condition. Combinational logic can be done as
follows:

And && Code runs while both conditions are true.


Or || Code runs if either condition is true.
Not ! Code runs if condition is not true.
*Remember the variable being tested needs an initial value and that value should change at some point.

Example C: Suppose a single LED is connected to pin 13 and blinks in intervals of ¼ s. Write a sketch to make
the LED blink slower and slower and resetting after its delay reaches 2 seconds.

➢ Since all Arduino codes loop continuously while power is supplied, the while structure is very similar to
if in Arduino and in many applications is essentially the same. However, they are not the same if there
are other components in the void loop. if is still a branch that will execute code based on a
condition. while is still a loop that will still on that iteration of the Arduino loop while the conidian is
met.
➢ A “do while loop” works the exact same way as a while loop, but it will execute once even if the
condition being tested does not work. The command to initiate a do while loop is simply “do”. The
syntax is:
do (condition){
//do stuff
Example D: Create a do while loop to make a light blink while a button is pressed.

2.4 for Loops

➢ A for loop runs for a defined number of times. The syntax is:

For(conditions) {
//do things
}

➢ In Arduino, we cannot simply provide a matrix of numbers to execute the loop for, we must have a 3
expressions in the ‘for’ statement definition, one to initialize the control variable, one to test whether
to continue the loop, and one to increment the control variable. For example:

for (c = 0; 0 < 5; c++){


[Link](“This is a lot easier in MATLAB.”);
}

The first time through the loop, c = 0 and the text is printed. The second time through the loop, c will 1
as ‘c++’ will increment c by 1. This will continue until the loop executes and c = 5, at which point the
statement will no longer loop. This works the same way as a “while” loop, except that the incrementing
is done in the statement definition.

Example E: Create a sketch that does the same thing on the example above, but uses a command to start c at 5
and decrement to 0.
Example F: Create a sketch that has an LED blink on and off 3 times.

2.5 Arrays

➢ An array is a collection of variables that are indexed with an index number. Here’s an example of an
array definition:

const int k_numLEDs = 4;

const int kPinLeds[k_numLEDs] = {2,3,4,5}

➢ The number of values in the array is defined first, then the individual values are defined as shown above.
The code above allows for 4 LED’s to be controlled at once.
➢ for loops are used to run sections of code for every element in an array.

Example G: Turn on 4 LED’s at once and then have them take turns getting dimmer over time.
Intro to Arduino
3 – Analog Input & Output
Objective: To program Arduino circuits with analog devices.

3.1 Analog Electronics

➢ In digital electronics, information can only be encoded in two ways “on/high/1” or “off/low/0”. As Obi-
Wan Kenobi tells Anakin Skywalker “only a Sith deals in absolutes”. An analog signal can take on any
number of values in a certain range. In short, analog is like turning a knob while digital is like flicking a
switch.

➢ Most circuit components (resistors, capacitors, diodes, etc.) are analog. Micro-controllers, such as the
Arduino Uno are digital. Arduino can work with Analog however by assigning discrete values to analog
input/outputs.

3.2 Analog Read & Write

➢ The Arduino Uno micro-controller has set of analog pins. The pins are named A0, A1, A2, etc. The
analogue pins can also be used as extra digital pins by naming A0 as 15 instead of A0, or A1 as 16, but
the digital pins cannot be used for analogue input/outputs. To set an input or output device as analog,
connect it to an analog pin on the Arduino micro-controller.

➢ To define A0 as an analog input: pinMode(A0, INPUT);.


Analog inputs take on a value in the range 0-1023. To read an input:
analogRead(A0);

➢ To define A0 as an analogue input: pinMode(A0, OUTPUT)


Analog outputs can be in the range of 0-255. To read an input:
analogWrite(A0, value);

➢ If you want to take an analog input and make an output for another device, you need to adjust the
ranges, as the range for write is smaller than the range for reading analog. To fix this, use the map
command.

➢ The map command scales values from one range to another range. The syntax for the
command is:

map(value, fromLow, fromHigh, toLow, toHigh)

For example, to re-map 0-1023 to 0-255 the command would be:

map(value, 0, 1023, 0, 255)


3.3 Potentiometers

➢ The potentiometer takes on different resistance values based on the turning


of the knob and thus provides a clear example of an analog device. While it
can function in a circuit without Arduino, hooking the potentiometer’s
middle pin up to analog pin in Arduino allows it to act as an analog input and
programmed accordingly.

Example A: Adjust the speed an LED blinks using a potentiometer.

3.4 The Photoresistor

➢ The photo resistor is an analog input, similar to the potentiometer in that the resistance of it varies. In a
photo resistor, the resistance changes based on the amount of light input. The resistance of a
photoresistor increase when the amount of light decreases.
➢ A Photoresistor is made of a semiconductor with very high resistance. When light falls on the
photoresistor, photons from light are absorbed by the semiconductor material and energy is transferred
to electrons which break up resulting in lower resistance and higher conductivity.
➢ A photoresistor is drawn as a resistor with arrows going into it to show light coming
in.

Example B: Adjust the brightness of an LED based on the current light level.
3.5 RGB LED’s

➢ An RBG LED is an integrated circuit consisting of 3 outputs, one for


each of three colors (red, green and blue). The schematic of the RGB
LED in the Arduino Uno kit is shown on the right. Turning only one of
the outputs on will simply make the LED that color, while having
multiple on will blend the color. The RGB outputs can act as digital
(on/off) or analog(adjust brightness).

Example C: Create a purple LED (blue and red).


Intro to Arduino
4 – More Programming in Arduino
Objective: To program the servo-motor and utilize functions in Arduino.

Focus Question: When is it useful to use a function in Arduino?

4.1 Servo Motors

A servo motor is a motor that allows control of the precise angular position. A servomotor is somewhat like an
analog output, but Arduino has special commands specifically to handle servo motors. Working with servo
motors in MATLAB requires defining a variable to represent the servo, identifying the pin, and programming
an angular position for the motor to go to. The commands are listed below. We will assume the name of the
servo is “servo1” for the following:

▪ To define a new servo motor, it needs put in as a variable. The command to do so is:

Servo servo1

This command goes before void setup.


▪ To tell Arduino the pin in which the servo is attached to the pin is:

[Link](1)

This command goes within void setup. Even though servo motors has modes beside “high” or “low”, the
servo connects to a digital pin. The middle wire of the servo is the one that connects to the input/output
pin.

▪ To move the servo to a certain angular position, the command is:

[Link](#);

This command tells the servo to go the angular position corresponding to # degrees.
▪ It’s important to note the input is angular position and not angular
displacement; it does move # degrees from its current position, it simply moves
to the position. For example, if the current position is 50°, and programmer
inputs [Link](52), the motor will only move 2° to its new position.
▪ The servo motor can only move within the domain of 0 degrees to 180 degrees.
Example A: Make a servo motor spin 180o and back to 0° in 15o increments. (A servo motor going 180 degrees
and back is called a “sweep”).

Example B: Make a potentiometer control a Servo Motor.


4.2 User-Defined Functions in Arduino

If a section of code is used multiple times, it usually more efficient to create a user-defined function. setup
and loop are both built-in functions to Arduino. Functions are used in the called in void loop and defined with
their own structure below. An example of a function structure is given below:
void setup(){
}

void loop(){
int a = 1;
b = 2
int c
c = afunction(a,b) //calls the function
}

int afunction(int a, int b){ //function defintion


int output
output = a+b;
return output
}

▪ The function name in the program above is “afunction”. The function is simply called by name in the
void loop and then defined at the bottom of the program after void loop.
▪ The return type of the function is int, which specifies what type of variable the output is. If there is
no output and the function just accomplishes a task as in Example C, the type of the function is void.
▪ The value of output is returned by the function. Since c is set equal to afunctin in void loop, c
will take on the value of output.
▪ The function has 2 inputs, a and b. The variable types of the input must be specified in the function
definition. A function does not need inputs.

Example C: Create a function to blink an LED attached to pin 10.


Intro to Arduino
5 – Serial Input & Output
Objective: To use the Serial Monitor to allow for input and output from the user in MATLAB.

4.1 The Serial Monitor

➢ The serial monitor in Arduino is used to pass information between the computer and the Arduino board.
This allows communication between a user and Arduino.
➢ The Serial Monitor can be opened by going to Tools -> Serial Monitor. It can be used to print text or
numbers to the screen and to interact with the user. The TX and RX pins are used to communicate
between Arduino and the computer.

5.2 Serial Output

➢ The programmer can print test or a variable value to the serial monitor to communicate with a user.
Before user the serial monitor in a program in any capacity, the [Link] command must be used.
The command to tell Arduino that you’re using the serial monitor is:
[Link](9600)
This command must always be included in void setup. 9600 is the baud, or the bits per second to
transmit. 9600 is the default setting.
➢ The commands to print to the serial monitor within the body of the program are:
• [Link](variable) - prints the value of a variable to the serial monitor.
• [Link](“Text”) – prints a string of text to the serial monitor.
• [Link]() – prints a variable or text and then starts a new line after printing the
specific output.

Example A: Print some text onto the Arduino Serial Monitor.


5.3 Sensing Temperature

➢ The temperature sensor is an integrated circuit that returns a value based on


the temperature of its surroundings.
➢ Temperature is obviously an analog value, so the temperature sensor must be
connected to an analog pin.
➢ The temperature sensor reads an analogue input between 0-255. This is
obviously not temperature. You can convert this reading to mV by the
formula:
5000
𝑉𝑜𝑙𝑡𝑎𝑔𝑒 = (𝑟𝑒𝑎𝑑𝑖𝑛𝑔 ∗ 1024)
➢ 500 mV corresponds to 0° C. Every increase or decrease of 1 C has an increase or decrease of 10 mV.
Therefore, the formula for conversion is:

𝑉𝑜𝑙𝑡𝑎𝑔𝑒 − 500
𝑇𝑒𝑚𝑝 =
10

Example B: Print the temperature using the sensor.


5.4 The ASCII Table and Variable Types

➢ The Serial Monitor can be used to accept input in a somewhat limited capacity. It accepts 1 character
inputs, and each character gets an integer variable. Characters are converted in numerical values based
on the ASCII table.
➢ Types of variables – So far, all variables have been int variables. Temperature can be stuff besides
integers, so here’s some other variable types in C:
• int – stores an integer (must be between -215 to 215-1)
• float – A number with a decimal point. Accurate to 6-7 places. Math is not as reliable with
float variables.
• char – Stores a single character in single quotes. Also, the home planet of the Zerg in Starcraft.
➢ Each char variable has a numerical value assigned to it. Common values are given in the ASCII table
shown below.

➢ Example: Suppose the user enters “1” on their keyboard. Arduino with take this as “49” if the variable is
defined as numeric. An easy fix is to simply subtract ‘0’ from the decimal value of the chart, as this
represent the start of 1 digit numbers.
5.5 Serial Input

➢ To read input. from the serial monitor, there are 2 commands required:
• int variable = [Link]() – Sets whatever the user inputs as the value of “variable”.
The variable name be whatever.
• while([Link]() == 0); - This command must accompany [Link]
on the next line to actually accept input. The command is a loop, with no commands to execute.
The command basically tells Arduino not to do another while nothing is entered by the user, so it
stops the program from continuing until the user enters something.

Example C: Use the Arduino to ask the user their most favorite number, then give the number back to them
because you’re a kind person and wouldn’t just keep their favorite number to yourself.

Example D: Suppose there are LED’s on pins 9, 10, and 11. Have the user pick an LED to turn on.

You might also like