Part3-Programming (2) 2
Part3-Programming (2) 2
• Setup( ) function
• Loop( ) function
setup():
• A function present in every Arduino sketch.
• Run once before the loop() function.
• The setup() function should follow the declaration of
any variables at the very beginning of the program
• used to set pinMode or initialize serial communication.
loop():
• A function present in every single Arduino sketch.
• This code happens over and over again
• reading inputs, triggering outputs, etc.
• The loop() is where (almost) everything happens
1. Declare variables at top
2. Initialize
• setup() – run once at beginning
3. Running
• loop() – run repeatedly, after setup()
Declare variable
void setup()
{
set pins
Example of a bare minimum program:}
void loop()
{
repeatable instruction
}
Declare variables at top
int inputVariable;
char x;
int inputVariable = 0;
y = y + 3;
x = x - 7;
i = j * 6;
r = r / 5;
Example
/* Math */
Monitor?
{
Serial.begin(9600); // set up Serial library at 9600 bps
“float” Serial.println(a);
Serial.print("b = ");
Serial.println(b);
Serial.print("c = ");
Run this program again. Serial.println(c);
Monitor?
Serial.print("a * c = "); // multiply
Serial.println(a * c);
Example:
x = 2; // x = 2
x += 4; // x now contains 6
x -= 3; // x now contains 3
x *= 10; // x now contains 30
x /= 2; // x now contains 15
3. Comparison operators
x == y (x is equal to y)
x != y (x is not equal to y)
x < y (x is less than y)
x > y (x is greater than y)
x <= y (x is less than or equal to y)
x >= y (x is greater than or equal to y)
4. Arduino - Control Statements
1. “if” condition
if (expression){
Block of statements;
}
if (someVariable > 50)
{ Expression ( comparison
operator)
// do something here
void setup()
{
initialization
// no setup needed
} condition
increment
void loop()
{
for (int i=0; i <= 255; i++)
{
analogWrite(PWMpin, i); statement
delay(10);
}
}
2. “while” loop
while(someVariable ?? value)
{
doSomething;
}
Example:
int button2Pin = 2;
buttonState = LOW;
while(buttonState == LOW)
buttonState = digitalRead(button2Pin);
}
3. “do … while” loop
do
{
doSomething;
}
while (someVariable ??
value);
Example:
do
{
x = readSensor();
delay(10);
}
while (x < 100); // loops if x < 100
Arduino - Digital I/O Functions
1. pinMode(pin, mode)