Unit 2 Arduino Programming
Unit 2 Arduino Programming
Arduino and C
Programming
1
Basic components of the
Arduino
Microcontroller
3
Agen Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial
da Monitor Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection
Diagrams/EEPROM Group Activities,
Post-490 Planning
4
The Arduino
● IDE
You can retrieve the IDE from the main arduino Tip:
website (arduino.cc) 1.Use Auto-
● The IDE is written in Java; however, the Format to clean
arduino only accepts programs written in C. your code
Therefore you must program in C. The IDE spacing
acts as a C Compiler. 2.Use Serial
Plotter to see
Verify: Checks if your program compiles (syntax Arduino Output
check) Upload: Uploads your program to the
Arduino.
New: Creates a new program file
Open: Open an existing arduino
program file Save: Allows you to save
the current program
Must Choose Appropriate
Arduino Board before
uploading programs & choose
the port on the computer the 9
How are Arduino Programs
Structured
void setup()
{ Code to run Title of
Program
once
}
void loop(){
Code to run repeatedly
}
dataType variableName;
Example:
int year;
Instantiating a Variable
Add equals sign
int x;
float
y; int
z;
x=
5;
y=
2.7;
z=
x+y;
What
is z
equal
to
above
? 10
Using the Serial
Monitor
The serial monitor allows you to see the output from the program
1. insert Serial.begin(baudRate); to initialize the
Located serial port
Here baudRate = Speed of Connection (higher is
faster; must match workstation baud). // i
want that baud
default baud rate is 9600;
13
Generating Random
Numbers
Two functions are available for working with random numbers. random() and randomSeed()
14
Agen Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial
da Monitor Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection
Diagrams/EEPROM Group Activities,
Post-490 Planning
15
if if/else if/else if
ifcontrol
(condition) { control control
Statement
1; if (condition) { if (condition)
Statement Statement 1; Statemen
2; etc. Statement t; else if
} 2; etc. (condition)
} Statemen
else t; else if
{ Statem (condition)
Example ents; Stat
} ement;
if (temperature > 100) else
{ Serial.println(“wow Exampl Stat
”!) ement;
Serial.println(“that’s e if (grade >
hot!”) Exampl
} 92) { 1
m
Numeric
Comparisons
18
Agen Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial
da Monitor Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection
Diagrams/EEPROM Group Activities,
Post-490 Planning
19
for whil do
for (statement1; condition; statement 2) e
while (condition){ do { while
{ Code statements Code statements Code statements
} } } while (condition);
You can initialize multiples variables in You can place loops inside of another loop. The trick to using inner
a for statement loop sis that you must complete the inner loop before you
complete the outer loop.
Example Example
21
Controlling
Break Statement LoopsContinue Statement
● You can use the break statement when you ● You can use the continue statement to control loops.
need to break out of a loop before the Instead of telling the Arduino to jump out of a loop, it tells
condition would normally stop the loop the Arduino to stop processing code inside the loop, but
still jumps back to the start of the loop
Example
Example:
int i;
int i; for (i = 0; i <= 10; i++){
for (i = 0; i <= 20; If ((i > 5) && (i < 10))
i++) { if (i Continue;
== 15)
Break; Serial.print(“The value of the counter at“);
Serial.print(“currently on iteration:”); Serial.println(i);
Serial.println(i); }
} Serial.println(“this is the end of the test”);
Serial.println(“This is the end of the
test”);
} 22
Agen Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial
da Monitor Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection
Diagrams/EEPROM Group Activities,
Post-490 Planning
23
Arra
ysin a block of memory, allowing you to reference the
An array stores multiple data values of the same data type
variables using the same variable name. It does it through an index value.
Example 3
int myarray[ ] = {20, 30, 40, 50 100};
24
Arrays
Determining the size of an Array Continued
Challenge Question 1: What is the array
‘myArray’ look like in the program below?
● You may not remember how
many data points are in your int myArray[3][4];
array for (int i = 0; counter < 3; i
● You can use the handy sizeof ++){ for (int j = 0; j
function
< 4; i++)
size = sizeof(myArray) / sizeof(int); { myArray[ i ] [ j ] =
1;
Example: }
}
for (counter =0; counter < (sizeof(value)/sizeof(int)); counter++)
{ Challenge Question 2: What is
//This will only iterate through number of points in syntactically wrong with the array below?
an array statements; How do i fix it?
}
char myArray[ ] = { “mon”, “tue”, “wed”, “thu”,
“fri”};
25
Strin
gsa word
A string value is a series of characters put together to create
or sentence
Format
Example
Manipulating Strings
27
Agen Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial
da Monitor Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection
Diagrams/EEPROM Group Activities,
Post-490 Planning
28
Functio
ns
You’ll often find yourself using the same code in multiple locations. Doing large chunks of these is a hassle. However,
functions make these a lot easier. You can encapsulate your C code into a function and then use it as many times as you
want.
Structure
TIP: Make sure you define your function outside of the
datatype setup and loop functions in your arduino code sketch.
functionName() { If you define a function inside another function, the
// code statements inner function becomes a local function, and you can't
} use it outside the outer function
To create a function that does not return any data
values to the calling program, you use the void data
type for the function definition
Void myFunction() {
Serial.println(“This is my first function”);
}
29
Using the function/Returning
a value
Using the Function Returning a Value
To return a value from the function
To use a function you defined in your
back to the main program, you end
sketch, just reference it by the
the function with a return statement
function name you assigned, followed
by parentheses return
value;
Global
Variables
Local
Variables
Defining
Global
Variables
3
Data structures allow us to define custom
Struc
data types that group related data elements
together into a single object. ts Full Example: Declaring and Calling
Before you can use a data structure in your struct sensorinfo {
sketch, you need to define it. To define a char date[9];
data structure in the Arduino, you can use int
the struct statement. Here is the generic indoortemp;
format for declaration int
outdoortemp
Format
;
void setup() {
struct name {
}morningTemps
// put your setup code here, to run
variable list
}; once: Serial.begin(9600);
strcpy(morningTemps.date,
"01/01/14");
Example of declaration
morningTemps.indoortemp = 72;
morningTemps.outdoortemp = 25;
struct sensorinfo {
Serial.print ("Today's date is ");
char date[9];
Serial.println(morningTemps.date);
int
Serial.print("The morning outdoor
indoortemp;
temperate is ");
int
outdoortemp Serial.println(morningTemps.outdoorte
mp);
} 3
;
Unio
ns
Unions allow you to have a variable take on different
data types
//Full Example:
Format Union{
union { float
//variable list analogInput;
}; Int digitalInput;
}sensorInput;
//Saving a value
Example
Union { sensorInput.analogInput =
float myFunction1();
analogInput; sensorInput.digitalInput =
myFunction2();
int digitalInput;
//Calling a value;
} sensorInput;
Serial.println(sensorInput.analogI
nput);
3
Serial.println(sensorInput.DigitalIn
Using
Libraries
Libraries allow you to bundle related functions
into a single file that the Arduino IDE can
compile into your sketches. Instead of having
to rewrite the functions in your code, you just
reference the library file from your code, and
all the library functions become available. This
is handy for Arduino Shields
#include
‘libraryheader’
Installing your
Referencing the Library
#include ‘EEPROM’
library
1. Open the Arduino IDE
Functions
2. Select the sketch from the
Library.functio
menu bar
n()
3. Select Import libraries
Ex. for the EEPROM Sample
from the submenu
library libraries
4. Select Add library from the
EEPROM.read(0); 3
list of menu options already
Input/Output Layout on
Arduino
37
Digital & Analog
I/O
Format Getting a reading from an input device:
analogRead(pin)
pinMode(pin, MODE);
39
Writing to
EEPROM
EEPROM is the long term memory in the Arduino. It keeps data stored even when powered off, like a
USB flash drive. Important Note: EEPROM becomes unreliable after 100,000 writes
40
Debugging
Applications
● Compiler will give you the line
code(s)
● Compiler will give you the error
● The line causing problems
may get highlighted
● Look up errors online
41