0% found this document useful (0 votes)
1 views41 pages

Unit 2 Arduino Programming

This document serves as an introduction to Arduino and C programming, covering essential topics such as the Arduino hardware, IDE, variable declaration, control flow, loops, arrays, strings, and functions. It provides detailed explanations of programming concepts, including variable scope, data types, and the use of the Serial Monitor for debugging. Additionally, it includes examples and tips for effective coding practices in Arduino projects.

Uploaded by

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

Unit 2 Arduino Programming

This document serves as an introduction to Arduino and C programming, covering essential topics such as the Arduino hardware, IDE, variable declaration, control flow, loops, arrays, strings, and functions. It provides detailed explanations of programming concepts, including variable scope, data types, and the use of the Serial Monitor for debugging. Additionally, it includes examples and tips for effective coding practices in Arduino projects.

Uploaded by

Akila V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Introduction to

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
}

● Programs get saved in Documents/Arduino on your


workstation
1
NAMING A
VARIABLE
Variables can consist of both uppercase (A-Z) and lowercase(a-z)
letters.
Variables can contain numbers 0 to 9, but cannot start with a number.
Variables may not have the same names as Arduino language
keywords, e.g. you cannot have a variable named float.
Variables must have unique names, i.e. you cannot have two
variables with the same name.
Variable names are case-sensitive, so Count and count are
two different variables.
Variables may not contain any special characters, except the
underscore (_).
Declaring and Instantiating
Variables
Declaring a Variable

dataType variableName;

Example:
int year;

Instantiating a Variable
Add equals sign

Exampl Declaring and Instantiating For Constants


e: int Simultaneously Add ‘const’ before
year; Example: dataType Example:
year = int year = 2017; const float pi =
1
2017; 3.14;
Scope of
Variables
● 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
9
Math
Standard Operators are built-in for use and can be
used with variables. Two examplesOperators
below:

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;

2. Printing to the serial monitor:


Serial.print(sum) // does not start a
new line Serial.println(sum) //starts a
new line
●delay(x): pauses the sketch for x milliseconds
3. Working

with time
delayMicroseconds(x): pauses the sketch for x microseconds
● micros(): Returns the number of microseconds since the arduino
was reset
● millis(): returns the number of milliseconds since the Arduino was
reset
11
Output on the Serial
Monitor

Note: You cannot concatenate the Serial output


Tip: use // to place a comment. Examples Ex.
above // this won’t work
Serial.println(“The sum is” + sum); 1
Advanced Math
Example Functions
int Temperature = -7;
int value =
abs(temperature);
Serial.println(value);

What does it print


above?

Note: The map() and contrain()


functions are mostly used with
sensors. They allow you to keep
values returned by the sensors within a
specific range that your sketch can
manage

13
Generating Random
Numbers
Two functions are available for working with random numbers. random() and randomSeed()

random(min, max) : returns a random number between min


and max -1 random(max) : returns a random number between
0 and max -1
randomSeed(seed): Initializes the random number generator, causing it to restart at an
arbitrary point in random sequence.

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

Compound Conditions Negating a condition check


int a ==
Example 1 Example 2
1; If (!(a
If ((a == 1) || (b If ((a == 1) && (b == == 1))
== 1)){ 2)) { Serial.println(“The ‘a’ variable
statements; statements; is not equal to 1”); Or just
} } if(!(a ==2)) use
Serial.println(“The ‘a’ variable != in 2
Using a switch
statement
Instead of doing a lot of if and else statement, it may be useful to
do a switch
Format Example
switch (var) switch
{
(grade)
case 23:
{ case ‘A’:
//do something when var
Serial.println(“you got higher than a
equals 23 break;
92”); break;
case 64:
case ‘B’:
//do something when var
Serial.println(“You got higher than a
equals 64 break;
80”); break;
default:
default:
// if nothing else matches, do
Serial.println(“You have dishonored the
the default
family”); break;
// default is
}
optional break;
}

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);

executes until condition is executes until condition is executes at least once,


met met and until condition is
met
Example Example Exampl
int i = 0;
e
int values[5] = {10, 20, 30, 40, 50}; int i = 0;
for (int counter = 0; counter < 5; counter while (i<3) {//hearts for Serial.println(“H
++){ Serial.print(“one value in days Serial.println(“ i i”); do {
the array is “ ); is : “ i); Serial.println(“my name
Serial.println(values[counter]); i++; is”); if(i==0)
} } Serial.println(“What”);
if(i==1)
Serial.println(“Who”); i+
+;
Loops
Using Multiple Variables
Continued
Nesting Loops

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

int a,b; int a,b;


For (a = 0, b = 0; a < 10; a++, b++){ for (a = 0; a < 10; a++){
Serial.print(“One value for (b = 0; b < 10; b+
is “); Serial.println(a); +){ Serial.print(“one
Serial.print(“ and the other value value is “);
is “); Serial.println(b); Serial.print(a);
} Serial.print(“and the other value
is “); Serial.println(b);
}
}

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.

Format Using Loops with Arrays


datatype variableName[size];
int values[5] = {10, 20, 30, 40, 50};
Example 1:
for (int counter = 0; counter < 5; counter
int myarray[10]; //able to store 10 values
++){ Serial.print(“one value in
myarray[0] = 20; //stores values in index 0
the array is “ );
myarray[1] = 30; // stores values in index
Serial.print(values[counter]);
1
}
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};

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

String name = “my text here”;

Example

String myName = “Jackie Chan”;

Manipulating Strings

String myName = “Jackie


Chan”;
Output: JACKIE
myName.toUpperCase(); 2
More String
Functions

Although you can


just create a char
array, Strings are
much easier to work
with! They have
many more
supported functions

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;

void setup() { The value can either a constant


Serial.begin(960 numeric or string value, or a variable
0) that contains a numeric or string
MyFunction(); value. However, in either case, the
Serial.println(“N data type of the returned value must
ow we’re back match the data type that you use to
to the main define the function
program”); int
} myFunction2() {
int value = 3
Passing Values to
Functions void
You will most likely want to pass values
into function. In the main program setup() {
code, you specify the values passed to Int returnValue;
a function in what are called Serial.begin(9600); Argumen
arguments, specific inside the function Serial.print(“The area of a 10
ts
parenthesis x 20 size room is “);
returnValue =
area(10,20);
returnValue = area(10,20); Serial.println(returnVal
ue);
void loop() }
The 10 and 20 are value arguments
{
Parameters
separated by a comma. To retrieve the
}
arguments passed to a function, the
function definition must declare what int area (int width, int
are called parameters. You do that in height) { int result =
the main function declaration line width * height; Return
} result;
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

Defining
Global
Variables

Write them before the setup()

loop. Ex: const float pi = 3.14;

Be careful in modifying global


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) 3
Calling Functions
Recursively

Recursion is when the function calls


itself to reach an answer. Usually a int factorial (int x) {
recursion function has a base value if (x <=1) return 1;
that it eventually iterates down to. else return x * factorial(x-
Many advanced algorithms use 1);
recursion to reduce a complex equation }
down one level repeatedly until they
get to the level defined by the base Remember you are allowed to call
value. other functions from inside a
function

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

Defining the library in your sketch

#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);

The pinMode function requires two parameters.


The pin parameter determines the digital Complete Example
interface number to set. The mode parameter void setup (){
determines whether the pin operates input or
Serial.begin(9600);
output mode. There are 3 values for interface
pinMode(A1,
mode setting:
INPUT);
INPUT - To set an interface for normal input }
mode OUTPUT - To set an interface for
output mode void loop() {
float reading =
analogRead(A1);
} 38
Reading Connection
Diagrams

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

You’ll first need to include a library file in your sketch


#include
#include <EEPROM.h>
<EEPROM.h> void
After you include the standard EEPROM library file, {setup()
for (int i = 0; i < 255;
you can use the two standard EEPROM functions in
i++)
EEPROM.write(i,
your code: } i);
read (address) - to read the data value stored
at the EEPROM location specified by address vvoid
write (address, value) - to read values to the {loop()
EEPROM location specified by address }

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

You might also like