Intro To Arduino Programming
Intro To Arduino Programming
C Programming
Presentation by:
Shamim Ahmed
1
Assumptions and Goals
Assumptions
● You have taken at least one programming course prior
Goal
● Be able to create applications on arduino using the following methods
○ Adding Shields (Accessories; Attachments)
○ Adding Libraries
○ Using control flows (If-Else, Do While, While loop)
○ Using functions (Methods: e.g. getVariable, setVariable, changeVariables)
○ Reading connection diagrams
○ Debugging applications
Why
● 495 will not be a success if the hardware does not complete its mission objectives. Faculty are eager to
see a working model. To improve something and make it work, you first must understand it
2
Agenda Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial Monitor
Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection Diagrams/EEPROM
Group Activities, Post-490 Planning
3
Arduino Models
Arduino’s are microcontrollers: mini-computers with their own memory, disk, and processor
4
Lights on an Arduino (Arduino UNO)
4 Lights on an Arduino
6
Basic components of the Arduino
Microcontroller
7
Agenda Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial Monitor
Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection Diagrams/EEPROM
Group Activities, Post-490 Planning
8
The Arduino IDE
● You can retrieve the IDE from the main arduino website Tip:
(arduino.cc) 1. Use Auto-Format
● The IDE is written in Java; however, the arduino only to clean your code
accepts programs written in C. Therefore you must spacing
program in C. The IDE acts as a C Compiler. 2. Use Serial Plotter
to see Arduino
Output
Verify: Checks if your program compiles (syntax 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
void setup() {
Code to run once Title of
Program
}
void loop(){
Code to run repeatedly
}
10
Declaring and Instantiating Variables
Declaring a Variable
dataType variableName;
Example:
int year;
Instantiating a Variable
Add equals sign
● Variable scope determines where the variable can be used in the sketch. There are two
variable scopes
○ Local Variables
■ Can only be used inside a function, and only appear inside that function block.
■ You won't see a local variable from the setup function in the loop function
○ Global Variables (Static Variables)
■ Can be used in ALL functions
■ Common to see them at the start of the sketch before the setup function
12
Math Operators
Standard Operators are built-in for use and can be used with
variables. Two examples below:
int x;
float y;
int z;
x = 5;
y = 2.7;
z = x+y;
What is z equal to above?
int x = 5;
float y = 2.7;
float z = x+y;
What is z equal to above?
14
Output on the Serial Monitor
16
Generating Random Numbers
Two functions are available for working with random numbers. random() and randomSeed()
17
Agenda Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial Monitor
Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection Diagrams/EEPROM
Group Activities, Post-490 Planning
18
if control if/else control if/else if control
if (condition) { if (condition) { if (condition)
Statement 1; Statement 1; Statement;
Statement 2; Statement 2; else if (condition)
etc. etc. Statement;
} } else if (condition)
else { Statement;
Statements; else
} Statement;
Format Example
switch (var) { switch (grade) {
case 23: case ‘A’:
//do something when var equals 23 Serial.println(“you got higher than a 92”);
break; break;
case 64: case ‘B’:
//do something when var equals 64 Serial.println(“You got higher than a 80”);
break; break;
default: default:
// if nothing else matches, do the default Serial.println(“You have dishonored the family”);
// default is optional break;
break; }
}
21
Agenda Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial Monitor
Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection Diagrams/EEPROM
Group Activities, Post-490 Planning
22
for while do while
for (statement1; condition; statement 2){ while (condition){ do {
Code statements Code statements Code statements
} } } while (condition);
executes until condition is met executes until condition is met executes at least once, and
until condition is met
You can initialize multiples variables in a for You can place loops inside of another loop. The trick to using inner loop sis
statement that you must complete the inner loop before you complete the outer loop.
Example Example
24
Controlling Loops
Break Statement Continue Statement
● You can use the break statement when you need ● You can use the continue statement to control loops. Instead of
to break out of a loop before the condition would telling the Arduino to jump out of a loop, it tells the Arduino to stop
normally stop the loop 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; i++) { If ((i > 5) && (i < 10))
if (i == 15) Continue;
Break;
Serial.print(“currently on iteration:”); Serial.print(“The value of the counter at“);
Serial.println(i); Serial.println(i);
} }
Serial.println(“This is the end of the test”); Serial.println(“this is the end of the test”);
}
25
Agenda Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial Monitor
Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection Diagrams/EEPROM
Group Activities, Post-490 Planning
26
Arrays
An array stores multiple data values of the same data type in a block of memory, allowing you to reference the variables using the
same variable name. It does it through an index value.
Example 2:
// assigns values to first 5 data locations (index 0-4)
Int myarray[10] = {20, 30, 40, 50, 100};
Example 3
int myarray[ ] = {20, 30, 40, 50 100};
27
Arrays Continued
Determining the size of an Array 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 array int myArray[3][4];
● You can use the handy sizeof function for (int i = 0; counter < 3; i ++){
for (int j = 0; j < 4; i++) {
myArray[ i ] [ j ] = 1;
size = sizeof(myArray) / sizeof(int); }
}
Example:
Challenge Question 2: What is
for (counter =0; counter < (sizeof(value)/sizeof(int)); counter++){ syntactically wrong with the array below?
//This will only iterate through number of points in an array How do i fix it?
statements;
} char myArray[ ] = { “mon”, “tue”, “wed”, “thu”, “fri”};
28
Strings
A string value is a series of characters put together to create a word or sentence
Format
Example
Manipulating Strings
30
Agenda Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial Monitor
Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection Diagrams/EEPROM
Group Activities, Post-490 Planning
31
Functions
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 setup
datatype functionName() { and loop functions in your arduino code sketch. If you define a
// code statements function inside another function, the 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”);
}
32
Using the function/Returning a value
34
Handling Variables inside Functions
One thing that causes problem for beginning sketch writers is the scope of a variable. He scope is where the variable can be referenced
within the sketch. Variables defined in function can have a different scope than regular variables. That is, they can be hidden from the rest
of the sketch. Functions use two types of variables:
Global Variables
Local Variables
Local variables are declared in the function code itself, separate from the rest of the sketch code. What’s interesting is that a local variable
can override a global variable (but not good practice) 35
Calling Functions Recursively
36
Data structures allow us to define custom data types
Structs
that group related data elements together into a
single object. Full Example: Declaring and Calling
Before you can use a data structure in your sketch, struct sensorinfo {
you need to define it. To define a data structure in char date[9];
the Arduino, you can use the struct statement. Here int indoortemp;
is the generic format for declaration int outdoortemp;
}morningTemps
Format
struct name { void setup() {
variable list // put your setup code here, to run 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 indoortemp; Serial.print("The morning outdoor temperate
int outdoortemp; is ");
}morningTemps, noonTemps, eveningTemps; Serial.println(morningTemps.outdoortemp);
} 37
Unions
Unions allow you to have a variable take on different data types
//Full Example:
Format Union{
union { float analogInput;
//variable list Int digitalInput;
}; }sensorInput;
//Saving a value
Example
Union { sensorInput.analogInput = myFunction1();
float analogInput; sensorInput.digitalInput = myFunction2();
int digitalInput;
} sensorInput;
//Calling a value;
Serial.println(sensorInput.analogInput);
Serial.println(sensorInput.DigitalInput);
38
Using Libraries
#include ‘libraryheader’
#include ‘EEPROM’
40
Digital & Analog I/O
Format Getting a reading from an input device:
analogRead(pin)
pinMode(pin, MODE);
41
Reading Connection Diagrams
42
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
43
Debugging Applications
44
Agenda Introduction to the Arduino Hardware
IDE, Variables, Operands, and the Serial Monitor
Control Flow
Loops
Arrays & Strings
Functions, Structs, and Unions
Libraries/IO/Connection Diagrams/EEPROM
Group Activities, Post-490 Planning
45
Group Practice Problems
1. Have the Arduino to create and save an excel sheet onto an SD card. Make the first row have
these cells in order:
"Sequence", "Day", "Month", "Date", "Year", "Hour", "Minute", "Second", "Temp F", "Sensor 1", "Sensor
2";
Tip: Look into the library SD.h in your IDE. There are examples of how to use each library given by the
authors (IDE>Files>Examples). Save the file as demo.csv. Use this link for more information on
connection setup.
2. Configure the time on the Arduino DS3231 board to the current time and date and save it. Then,
create a program that gets the current month, day, year, hour, minute, second, and temperature. Set the
delay to 3000 milliseconds
Tip: Search for and download the Library Sodaq_DS3231.h from your IDE. It is not a pre-installed
library but you can easily find it by searching it in your IDE library manager. There are examples of how
to use each library given by the authors (IDE>FILES>Examples). 46