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

Es Arduino 4

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

Es Arduino 4

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

Lecture 4

Arduino Programming
Language

1
Arduino Programming Language
• Arduino – Tutorials
– http://arduino.cc/en/Tutorial/HomePage
• Arduino - Reference
– http://arduino.cc/en/Reference/HomePage
• Arduino – Libraries
– http://arduino.cc/en/Reference/Libraries

2
Binary and Hexadecimal Numbers - 1
 Microcontrollers are fundamentally digital
(as opposed to ‘analog’) and use binary
logic
 Two states: high and low, 1 or 0, on or off
 Often 5V or 0V
 One binary digit is called a bit
 It can take on two possible states: 1 or 0
 Four binary digits are called a nibble
 Eight binary digits are called a byte
 A word is a larger grouping: usually 32 bits

3
Binary and Hexadecimal Numbers - 2
 Byte and bits

1 1 0 0 1 1 0 1
Bit No. 7 6 5 4 3 2 1 0
Upper nibble Lower nibble
(4 bits) (4 bits)

MSB LSB
(Most Significant Bit) (Least Significant Bit)

4
Binary and Hexadecimal Numbers - 3
Place Value

1 1 3 8 (Base 10 or decimal number)

1  103  1  102  3  101  8  100


1000  100  30 8  1138 (Base 10)

Bit No. 3 2 1 0

1 1 0 1
(Base 2 or binary number )

1 23  1 22  0  21  1 20
8 4 0  1  13 (Base 10)

• What range of decimal values can 4 bits represent? 0 to 15


• How many values in total can 4 bits represent? 16
5
Binary and Hexadecimal Numbers - 4
Binary HEX
0 0 0 0 0 Why is hex important?
0 0 0 1 1
0 0 1 0 2
One hex digit can be
0 0 1 1 3
used as shorthand to
0 1 0 0 4 represent four binary
0 1 0 1 5 digits
0 1 1 0 6
0 1 1 1 7
Two hex digits can be
1 0 0 0 8 used as shorthand to
1 0 0 1 9 represent eight
1 0 1 0 A binary digits or one
byte
1 0 1 1 B
1 1 0 0 C
1 1 0 1 D
1 1 1 0 E
1 1 1 1 F
6
Binary and Hexadecimal Numbers - 5

 Convert each hex digit into 4 bits.


 Convert binary to decimal.
Example:

convert the hexadecimal number A616 into its


binary
A 6 16
 A616 = 101001102
1010 0110

7
Structure

Arduino programs run on two basic sections:

void setup()
{

//setup motors, sensors etc


}

void loop()
{
// get information from sensors
// send commands to motors
8
}
void setup()
• The setup section is used for assigning input
and outputs (Examples: motors, LED’s,
sensors etc) to ports on the Arduino
• It also specifies whether the device is
OUTPUT or INPUT
• To do this we use the command “pinMode”
• Setup is called once, when the sketch starts.

9
SETUP

void setup()
{
pinMode(9, OUTPUT);
}

10
void loop()
 loop( ) runs over and over, until power is lost or a
new sketch is loaded.

Void loop( ) {} is equivalent to while(1) { }

 You need to include both functions in your


sketch, even if you don't need them for anything.

 The “( )” in the header is where you declare any


variables that you are “passing” (or sending) the
function, the loop function is never “passed” any
11
variables
void loop()

void loop()
{ Port # from setup

digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(1000);
Turn the LED on
} or off
Wait for 1 second
or 1000 milliseconds 12
void loop()

13
Structure - Control Structures
 if
 if...else
 for
 switch case
 while
 do... while

14
“if” condition
 “if”, which is used in conjunction with a comparison
operator, tests whether a certain condition has been reached, such
as an input being above a certain number. The format for an “if”
test is:
if (someVariable > 50)
comparison
{ operator
// do something here
}
 The program tests to see if someVariable is greater than 50. If
it is, the program takes a particular action.
 If the statement in parentheses is true, the statements inside the
brackets are run. If not, the program skips over the code.
Example:
if (x > 120) digitalWrite(LEDpin, HIGH);

15
“if-else”
The “if-else” is the primary means of conditional branching.
To branch an execution of your program depending on the state of a
digital input, we can use the following structure:

if (inputPin == HIGH)
{
doThingA;
}
else
{
doThingB;
}

16
“if-else”

17
“for” statement
 The “for” statement is used to repeat a block of statements
enclosed in curly braces. An increment counter is usually used to
increment and terminate the loop. The “for” statement is useful
for any repetitive operation:
for (initialization; condition; increment)
{
//statement(s);
}
 The “initialization” happens first and exactly once. Each
time through the loop, the “condition” is tested; if it's true, the
“statement” block, and the “increment” is executed, then the
“condition” is tested again. When the “condition” becomes
false, the loop ends.

18
“for” statement
Example :
“Dim LED using a PWM pin”:

int PWMpin = 10; // LED in series with 1k resistor on pin 10

void setup()
{
// no setup needed initialization
} condition

void loop() increment


{
for (int i=0; i <= 255; i++)
{ statement
analogWrite(PWMpin, i);
delay(10);
}
} 19
“switch ... case”
 Switch...case controls the flow of programs by allowing
programmers to specify different code that should be executed in
various conditions.
 When a case statement is found whose value matches that of
the variable, the code in that case statement is run.
Example:
switch (var)
{
case label:
// statements
break;
case label:
// statements
break;
default:
// statements
} 20
switch ... case
• void loop() {
// read the sensor:
int sensorReading = analogRead(A0);
// map the sensor range to a range of four options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

// do something different depending on the


// range value:
switch (range) {
case 0: // your hand is on the sensor
Serial.println("dark");
break;
case 1: // your hand is close to the sensor
Serial.println("dim");
break;
case 2: // your hand is a few inches from the sensor
Serial.println("medium");
break;
case 3: // your hand is nowhere near the sensor
Serial.println("bright");
break;
}
delay(1); // delay in between reads for stability
} 21
“while” loop
 While loops will loop continuously, and infinitely, until the
expression inside the parenthesis, () becomes false. Something
must change the tested variable, or the while loop will never exit.
This could be in your code, such as an incremented variable, or
an external condition, such as testing a sensor.
while(someVariable ?? value)
{
doSomething;
}
Example:
const int button2Pin = 2;
buttonState = LOW;
while(buttonState == LOW)
{
buttonState = digitalRead(button2Pin);
}

22
“do … while” loop
 The “do” loop works in the same manner as the “while” loop,
with the exception that the condition is tested at the end of the
loop, so the “do” loop will always run at least once.
do
{
doSomething;
}
while (someVariable ?? value);

Example:
do
{
x = readSensor();
delay(10);
}
while (x < 100); // loops if x < 100

23
Structure - Further Syntax
 ; (semicolon)
 {} (curly braces)
 // (single line comment)
 /* */ (multi-line comment)
 #define
 #include

24
Structure - Arithmetic Operators
 = (assignment operator)
 + (addition)
 - (subtraction)
 * (multiplication)
 / (division)
 % (modulo)

25
Example
/* Math */

int a = 5;
int b = 10;
int c = 20;

void setup()
{
Serial.begin(9600); // set up Serial library at 9600 bps

Serial.println("Here is some math: ");

Serial.print("a = ");
Serial.println(a);
Serial.print("b = ");
Serial.println(b);
Serial.print("c = ");
Serial.println(c);

Serial.print("a + b = "); // add


Serial.println(a + b);

Serial.print("a * c = "); // multiply


Serial.println(a * c);

Serial.print("c / b = "); // divide


Serial.println(c / b);

Serial.print("b - c = "); // subtract


Serial.println(b - c);
}

void loop() // we need this to be here even though its empty


{
}

26
Structure - Compound Operators
 ++ (increment)
 -- (decrement)
 += (compound addition)
 -= (compound subtraction)
 *= (compound multiplication)
 /= (compound division)
 &= (compound bitwise and)
 |= (compound bitwise or)
27
Compound Operators
Increment or decrement a variable
X ++ // same as x = x + 1, or increments x by +1
X -- // same as x = x – 1, or decrements x by -1
X += y // same as x = x + y, or increments x by +y
X -= y // same as x = x - y, or decrements x by -y
X *= y // same as x = x * y, or multiplies x by y
X /= y // same as x = x / y, or divides x by y

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

28
Structure - Comparison Operators
 == (equal to)
 != (not equal to)
 < (less than)
 > (greater than)
 <= (less than or equal to)
 >= (greater than or equal to)

29
Example

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)

30
Structure - Boolean Operators
|| (or)
 && (and)
 ! (not)

31
Boolean Operators - OR
 If we want either of the conditions to be
true we need to use ‘OR’ logic (OR gate)
 We use the symbols ||

Example:

if ( val < 10 || val > 20)

32
Boolean Operators - AND
 If we want all of the conditions to be true
we need to use ‘AND’ logic (AND gate)
 We use the symbols &&

Example

if ( val > 10 && val < 20)

33
Structure - Bitwise Operators
 & (bitwise and)
 | (bitwise or)
 ^ (bitwise xor)
 ~ (bitwise not)
 << (bitshift left)
 >> (bitshift right)

34
Bitwise Operators
const int outPin = 7;
cost byte myByte = B00101010;
void setup(void) {
pinMode(outPin, OUTPUT);
}
void loop(void) {
for (int ii = 0; ii < 7; ii++) {
if (myByte & (B10000000 >> ii)) {
digitalWrite(outPin, HIGH);
}
else {
digitalWrite(outPin, LOW);
}
35
}
Format of variables
value
 A variable is like “bucket”
 It holds numbers or other values temporarily
 All variables have to be declared before they are
used.
 Declaring a variable means defining its type, and
optionally, setting an initial value (initializing the
variable).
 int val = 5;

assignment value
Type variable name 36
“becomes”
37
Variable Types
Variable Types:

8 bits 16 bits 32 bits

byte int long


char unsigned int unsigned long
float
38
Variables - Data Types
 void
 boolean
 char
 unsigned char
 byte
 int
 unsigned int
 word
 long
 unsigned long
 float
 double
 string - char array
 String - object
39
 array
void
 The “void” in the header is what the function will
return (or spit out) when it happens, in this case
it returns nothing so it is void

void setup()
{

}
void loop()
{

40
Declaring/ Assigning Variables

Boolean

boolean variableName;
Boolean variableName = true;

41
char
42
 A data type that takes up 1 byte of memory that
stores a character value. Character literals are
written in single quotes, like this: 'A' (for multiple
characters - strings - use double quotes:
"ABC").

 Characters are stored as numbers however. You


can see the specific encoding in the ASCII chart.

Example
 char myChar = 'A';
 char myChar = 65; // both are equivalent
ASCII Table
43
byte
44

 A byte stores an 8-bit unsigned number, from 0


to 255.
Example
 byte b = B00010010; // "B" is the binary
formatter (B00010010 = 18 decimal)
int
45  Integers are your primary datatype for number
storage, and store a 2 byte value. This yields a
range of -32,768 to 32,767 (minimum value of -
2^15 and a maximum value of (2^15) - 1).

 Int's store negative numbers with a technique


called 2's complement math. The highest bit,
sometimes refered to as the "sign" bit, flags the
number as a negative number. The rest of the
bits are inverted and 1 is added.

Example
 int var = val;
unsigned int
46

 Unsigned ints (unsigned integers) are the same


as ints in that they store a 2 byte value. Instead
of storing negative numbers however they only
store positive values, yielding a useful range of
0 to 65,535 (2^16) - 1).

Example
 unsigned int var = val;
long
47

 long – long variables are extended size


variables for number storage, and store 32
bits (4 bytes), from −2,147,483,648 to
2,147,483,647.
 unsigned long – unsigned long variables are
extended size variables for number storage,
and store 32 bits (4 bytes). Unlike standard
longs unsigned longs won't store negative
numbers, making their range from 0 to
4,294,967,295
float / double
48  float – datatype for floating-point numbers, a
number that has a decimal point. They are often used
to approximate analog and continuous values
because they have greater resolution than integers.
Floating-point numbers can be as large as
3.4028235E+38 and as low as −3.4028235E+38.
They are stored as 32 bits (4 bytes) of information.
 double – double precision floating point number.
Occupies 4 bytes. The double implementation on the
Arduino is currently exactly the same as the float, with
no gain in precision.
Variable Scope
Where you declare your variables matters
49
Functions - Digital I/O
 Digital inputs will come to the Arduino as either
on or off (HIGH or LOW, respectively).
– HIGH is 5VDC.
– LOW is 0VDC.
 pinMode()
 digitalWrite()
 digitalRead()

50
pinMode()
51

 The pinMode() function configures a pin as


either an input or an output. To use it:
 You pass it the number of the pin to configure and
the constant INPUT or OUTPUT.
 pinMode(11, INPUT);
 pinMode(13, OUTPUT);
 When configured as an input, a pin can detect the
state of a sensor like a pushbutton.
 As an output, it can drive an actuator like an LED.
digitalWrite()
52

 The digitalWrite(pin, value) functions outputs a


value on a pin.
 Possible values are:
 LOW (0 V)or

 HIGH (5 V)

 For example:
 digitalWrite(13, HIGH);
 digitalWrite(11, LOW);
digitalRead()
53

 The digitalRead(pin) reads a digital value on a


pin set for input.
 Possible values are:
 LOW (0 V)or

 HIGH (5 V)

 digitalRead(10);
Functions - Analog I/O
 Analog inputs will come to the Arduino as a
range of numbers, based upon the electrical
characteristics of the circuit.
– 0 to 1023
– .0049 V per digit (4.9 mV)
– Read time is 100 microseconds (10,000 a
second)
 analogRead()
 analogWrite() - PWM
54
analogWrite()
 Writes an analog value (PWM wave) to a pin.

 Can be used to light a LED at varying brightnesses or


drive a motor at various speeds.

 After a call to analogWrite(), the pin will


generate a steady square wave of the specified duty
cycle .
For example:
analogWrite(pin, value)

pin: the pin to write to.


value: the duty cycle: between 0 (always off) and 255
55
analogRead()
 Arduino uses a 10-bit A/D Converter:
• this means that you get input values from
0 to 1023
• 0V0
• 5 V  1023

 For example:
int sensorValue = analogRead(A0);

56
Example
PWM. LED fading
/* Fading
This example shows how to fade an LED using the analogWrite() function.
The circuit: LED attached from digital pin 9 to ground.
*/

int ledPin = 9; // LED connected to digital pin 9

void setup()
{
// nothing happens in setup
}

void loop()
{
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue++) // fade in from min to max in
increments
{
analogWrite(ledPin, fadeValue); // sets the value (range from 0 to 255)
delay(2); // wait for x milliseconds to see the dimming effect
}

for(int fadeValue = 255 ; fadeValue >= 0; fadeValue--) // fade out from max to min in
increments
{
analogWrite(ledPin, fadeValue); // sets the value (range from 0 to 255)
delay(2); // wait for x milliseconds to see the dimming effect
}
}

57
Functions - Time
 millis(): get the current time
delay(ms): Pauses for a few milliseconds
 delayMicroseconds(us): Pauses for a few
microseconds

58
Functions - External Interrupts

 attachInterrupt()
 detachInterrupt()

59
attachInterrupt()
 On a standard Arduino board, two pins
can be used as interrupts: pins 2 and 3.
The interrupt is enabled through the
following line:
 attachInterrupt(interrupt, function, mode)
attachInterrupt(0, doEncoder, FALLING);

60
attachInterrupt()
 Interrupt: the number of the interrupt, 0 or 1,
corresponding to Arduino pins # 2 and 3
respectively

 Function: the function to call when the


interrupt occurs

 Mode: defines when the interrupt should be


triggered

61
mode

• LOW whenever pin state is low


• CHANGE whenever pin changes value
• RISING whenever pin goes from low to high
• FALLING whenever pin goes from low to high

Don’t forget to CAPITALIZE

62
Interrupt example
int led = 7;
int state = LOW;
void setup()
{
pinMode(led, OUTPUT);
attachInterrupt(1, blink, CHANGE);
}
void loop()
{
digitalWrite(led, state);
}
void blink()
{
state = !state;
}
63
Functions - Communication

• Serial
• Stream

64

You might also like