Coding blink

Download Report

Transcript Coding blink

Introduction to Coding
1
Example
Codes
A lot of example
codes are given
with Arduino IDE
A code can often be based
on a previous example
rather than being created
from scratch
2
Blink
A simple
code used to
blink an LED
plugged into
pin 13
The following slides will go
through the ‘blink’ code in
detail, line by line
3
Comments
• The first lines of code are displayed in gray
• This indicates that they are comments for humans to read
and not part of the actual code
4
Comments
• There are 2 ways to incorporate a comment into a code
• // ….. - Single line comment
• /* ….. */ - Multiline comment
5
Variables
• The next line of code introduces a variable called ‘led’ and
sets it equal to 13
• The name of the variable is chosen by the programmer
• In this case ‘x = 13’ or ‘table = 13’ would all suffice
• It is common to choose a variable name that correlates to
what it is being used for
• In this case 13 will represent the pin the LED is plugged into
6
Variables
• The word ‘int’ preceding the variable name is used to tell the
Arduino what we plan on storing in the variable ‘led’
• ‘int’ type can store any integer between ±32,768. It cannot
store a fraction or decimal
• ‘long’ type has a range of ± 2,147,483,648. However, it uses up
more memory
• ‘float’ type has a range of ± 3.4028235E+38. It can contain
decimals
7
Routines
• Each Arduino program is called a SKETCH and has two
required functions, called ROUTINES. One is the ‘setup’ and
one is the ‘loop’
• Each routine contains all of its coding within curly braces
• void setup ( ) { } - runs once when the program begins
• void loop ( ) { } - runs repeatedly forever
8
pinMode
• In this routine there is only one line of code, ‘pinMode’
• Each digital pin, 0 – 13, needs to be declared as either
INPUT or OUTPUT
• An Input is constantly waiting to absorb voltage while an
OUTPUT is waiting to be told to supply it outward
• In this case pin 13, with an LED, is an Output. We use the
‘led’ in place of ‘13’ since we already declared led = 13;
9
digitalWrite
• The next piece of code is the ‘void loop’ routine of the sketch
• An output pin can be set HIGH (5v ON) or LOW (0v OFF) using
the digitalWrite command
• We declared led = 13 so we can write ‘led’ as the pin #
• HIGH means to turn on the pin, or send out 5V through pin 13
10
delay
• The ‘delay ’ function causes the Arduino to pause
• delay is measured in milliseconds, so 1000 = 1 second
• In this ‘loop’ the first line turns on a LED plugged into pin 13,
and the second line tells the controller to wait for 1 second
11
Run
To compile your sketch,
click the checkmark.
Make sure your Arduino
is plugged into an
available USB port.
Click the arrow to
download the program
to Arduino. If everything
is attached correctly. The
LED should blink.
12