0% found this document useful (0 votes)
72 views

Intro To Arduino Programming

This document provides an introduction and overview of Arduino and C programming. It discusses: - The goals of learning to program Arduinos using shields, libraries, control flows, functions, and debugging. - An overview of the Arduino hardware including models, lights, accessories, and shields. - How to structure Arduino programs using setup() and loop() functions. - Programming concepts like declaring variables, math operators, serial monitor output, and control flows. - Additional topics like loops, arrays, functions, libraries, and debugging.

Uploaded by

Jagtap anuj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Intro To Arduino Programming

This document provides an introduction and overview of Arduino and C programming. It discusses: - The goals of learning to program Arduinos using shields, libraries, control flows, functions, and debugging. - An overview of the Arduino hardware including models, lights, accessories, and shields. - How to structure Arduino programs using setup() and loop() functions. - Programming concepts like declaring variables, math operators, serial monitor output, and control flows. - Additional topics like loops, arrays, functions, libraries, and debugging.

Uploaded by

Jagtap anuj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Introduction to Arduino and

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

1. ON Light - shows that it is powered on


2. TX Light - shows that data is being
transmitted
3. RX Light - shows that data is being received
4. L Light - an LED you are able to control in your
program

Serial Port (USB)

External Power Source (AA,


AAA Batteries)
5
Arduino Accessories & Shields
● Accessories include USB A-B cable, external power source, breadboard, resistors, variable resistors
(potentiometers), switches, wires, sensors, motors
● Shields” are add ons or accessories that extend the functionality of Arduino. The code is already written for
them
○ Ethernet Shields
○ LCD Shields
○ Motor Shields extends the number of motors you can use on an arduino from 6
○ Prototype Shield - for circuit development rather than soldering
■ Use breadboard as an alternative to this shield
○ There are many more shields including bluetooth, wireless, etc.
● Arduino models allow you to connect a battery or AC/DC converter to run without being connected to a computer

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

Must Choose Appropriate Arduino


Board before uploading programs
& choose the port on the computer
the arduino is connected to 9
How are Arduino Programs Structured

void setup() {
Code to run once Title of
Program
}

void loop(){
Code to run repeatedly
}

● Programs get saved in Documents/Arduino on your workstation

10
Declaring and Instantiating Variables
Declaring a Variable

dataType variableName;

Example:
int year;

Instantiating a Variable
Add equals sign

Example: Declaring and Instantiating For Constants


int year; Simultaneously Add ‘const’ before dataType
year = 2017; Example: Example:
int year = 2017; const float pi = 3.14;
11
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

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?

Tip: instead of x = x + 1; you can write x += 1;


13
Using the Serial Monitor
The serial monitor allows you to see the output from the program
1. insert Serial.begin(baudRate); to initialize the serial port
Located 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

3. Working with time


● delay(x): pauses the sketch for x milliseconds
● 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

14
Output on the Serial Monitor

Note: You cannot concatenate the Serial output


Tip: use // to place a comment. Examples above Ex.
// this won’t work
Serial.println(“The sum is” + sum); 15
Advanced Math Functions
Example

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

16
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.

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;

Example Example Example

if (temperature > 100) { if (grade > 92) { if (grade > 92) {


Serial.println(“wow”!) myGrade = ‘A’; myGrade = ‘A’;
Serial.println(“that’s hot!”) else else if (grade > 83)
} myGrade = ‘F’; myGrade = ‘B’;
else
myGrade = ‘C’; 19
Numeric Comparisons

Compound Conditions Negating a condition check


int a == 1;
Example 1 Example 2
If (!(a == 1))
If ((a == 1) || (b == 1)){ If ((a == 1) && (b == 2)) { Serial.println(“The ‘a’ variable is not
statements; statements; equal to 1”);
} } if(!(a ==2)) Or just use
Serial.println(“The ‘a’ variable is not != in the
equal to 2”); condition 20
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 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

Example Example Example


int values[5] = {10, 20, 30, 40, 50}; int i = 0; int i = 0;
for (int counter = 0; counter < 5; counter ++){ while (i<3) {//hearts for days Serial.println(“Hi”);
Serial.print(“one value in the array is “ ); Serial.println(“ i is : “ i); do {
Serial.println(values[counter]); i++; Serial.println(“my name is”);
} } if(i==0) Serial.println(“What”);
if(i==1) Serial.println(“Who”);
i++;
} while (i < 2);
Serial.println(“slicka chika slim shady”); 23
Loops Continued
Using Multiple Variables Nesting Loops

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

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 is “); for (b = 0; b < 10; b++){
Serial.println(a); Serial.print(“one value is “);
Serial.print(“ and the other value is “); Serial.print(a);
Serial.println(b); Serial.print(“and the other value is “);
} Serial.println(b);
}
}

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.

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 the array is “ );
myarray[0] = 20; //stores values in index 0
Serial.print(values[counter]);
myarray[1] = 30; // stores values in index 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};

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

String name = “my text here”;

Example

String myName = “Jackie Chan”;

Manipulating Strings

String myName = “Jackie Chan”;


myName.toUpperCase();

Output: JACKIE CHAN 29


More String Functions

Although you can just


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

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

Using the Function Returning a Value


To return a value from the function back to
To use a function you defined in your sketch,
the main program, you end the function with
just reference it by the function name you
a return statement
assigned, followed by parentheses
return value;
void setup() {
Serial.begin(9600) The value can either a constant numeric or
MyFunction(); string value, or a variable that contains a
Serial.println(“Now we’re back to the main program”); numeric or string value. However, in either
} case, the data type of the returned value
must match the data type that you use to
define the function
int myFunction2() {
int value = 10*20;
return (value);
} 33
Passing Values to Functions
You will most likely want to pass values into void setup() {
function. In the main program code, you
specify the values passed to a function in Int returnValue;
what are called arguments, specific inside the Serial.begin(9600); Arguments
function parenthesis Serial.print(“The area of a 10 x 20
size room is “);
returnValue = area(10,20);
returnValue = area(10,20); Serial.println(returnValue);
}
The 10 and 20 are value arguments
separated by a comma. To retrieve the void loop() {
Parameters
arguments passed to a function, the function }
definition must declare what are called
parameters. You do that in the main function int area (int width, int height) {
declaration line int result = width * height;
Return result;
}

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

Defining Global Variables

Write them before the setup() loop. Ex:

const float pi = 3.14;

Be careful in modifying global variables.

Declaring 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

Recursion is when the function calls itself to


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

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

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’
#include ‘EEPROM’

Installing your library


Referencing the Library Functions
1. Open the Arduino IDE
2. Select the sketch from the menu bar
Library.function()
3. Select Import libraries from the
submenu
Ex. for the EEPROM library Sample libraries
4. Select Add library from the list of
EEPROM.read(0); already installed
menu options
for call and use 39
Input/Output Layout on Arduino

40
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 interface number Complete Example
to set. The mode parameter determines whether the void setup (){
pin operates input or output mode. There are 3 values
Serial.begin(9600);
for interface mode setting:
pinMode(A1, INPUT);
INPUT - To set an interface for normal input mode }
OUTPUT - To set an interface for output mode
void loop() {
float reading = analogRead(A1);
}

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

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


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

43
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

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

You might also like