You are on page 1of 109

Dr.

Triwiyanto
Syevana Dita M., ST
Expertise on embedded system,
biomedical signal processing,
rehabilitation engineering
WA: 081-5512-6883
Email: triwiyanto123@gmail.com

Introduction to...

Arduino
This semester: 12 meeting & 2 exam
1. Introduction Arduino (a demonstration video)
2. Instruction (arith., compar., logical, cond., loop)
3. Analog read
4. Analog write
5. Motor (DC/ Servo/ Stepper)
6. Mid Test (UTS)
7. SPI/ I2C
8. DHT11 temp./humidity
@meeting:
9. TCS32000 color sensor
1. Lecturing: 30 minute
10.RTC DS1307
2. Exercise: 20 minute
11.MPU 6050 Acc/Gyro
3. Assignment: 5 minute
12.Student presentation
4. Closing: 5 minute
13.Student presentation
14.Final test
Micro-Controller:

It is a micro-computer.
As any computer it has
internal CPU, RAM, IOs
interface.
It is used for control
purposes, and for data
analysis.

Famous microcontroller manufacturers are MicroChip,


Atmel, Intel, Analog devices, and more.
What is a Development Board

• A printed circuit
board designed to
facilitate work with a
particular
microcontroller.
• Typical components include:
• power circuit
• programming interface
• basic input; usually buttons and LEDs
• I/O pins
What is Arduino Not?

• It is not a chip (IC)


• It is not a board (PCB)
• It is not a company or a manufacturer
• It is not a programming language
• It is not a computer architecture
Arduino.

(although it involves all of these things...)


So, what is the Arduino

todbot.com/blog/bionicarduino
What is Arduino?
A microcontroller board, contains on-board
power supply, USB port to communicate with PC,
and an Atmel microcontroller chip.
It simplify the process of creating any control
system by providing the standard board that can
be programmed and connected to the system
without the need to any sophisticated PCB design
and implementation.
Arduino.

It is an open source hardware, any one can


get the details of its design and modify it or
make his own one himself.
Arduino – Official Definition
Taken from the official web site
(arduino.cc):
– Arduino is an open-source electronics
prototyping platform based on flexible,
easy-to-use hardware and software.

– It's intended for artists, designers,


hobbyists, and anyone interested in
creating interactive objects or
environments.
Why Arduino?
• For whatever reason, Arduino
microcontrollers have become the de facto
standard.
– Make Magazine features many projects using
Arduino microcontrollers.
• Strives for the balance between ease of use
and usefulness.
– Programming languages seen as major obstacle.
– Arduino C is a greatly simplified version of C++.
• Inexpensive (35k retail).
Arduino boards:

UNO Mega LilyPad

Arduino BT Arduino Nano Arduino Mini


Arduino UNO:
Digital output
~: PWM. In circuit Serial
0,1: Serial port. programming

Atmel
MicroController
USB port

Power input

Analog input.
Power Supply
Arduino Program Development
• Based on C++ without 80% of the instructions.
• A handful of new commands.
• Programs are called 'sketches'.
• Sketches need two functions:
– void setup( )
– void loop( )
• setup( ) runs first and once.
• loop( ) runs over and over, until power is lost or a
new sketch is loaded.
Terminology
Arduino C
• Arduino sketches are centered around the
pins on an Arduino board.
• Arduino sketches always loop.
– void loop( ) {} is equivalent to while(1) { }
• The pins can be thought of as global variables.
Digital I/0

pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT
digitalRead(pin)
Reads HIGH or LOW from a pin
digitalWrite(pin, value)
Writes HIGH or LOW to a pin
Arduino Timing

• delay(ms)
– Pauses for a few milliseconds
• delayMicroseconds(us)
– Pauses for a few microseconds
• More commands:
arduino.cc/en/Reference/HomePage
Compiler Features
• Numerous sample
sketches are included in
the compiler
• Located under File,
Examples
• Once a sketch is
written, it is uploaded
by clicking on File,
Upload, or by pressing
<Ctrl> U
Arduino C is Derived from C++
◼ These programs blink an LED on pin 13
• avr-libc • Arduino C
#include <avr/io.h> void setup( ) {
#include <util/delay.h> pinMode(13, OUTPUT);
}
int main(void) {
while (1) { void loop( ) {
PORTB = 0x20; digitalWrite(13, HIGH);
_delay_ms(1000); delay(1000);
PORTB = 0x00; digitalWrite(13, LOW);
_delay_ms(1000); delay(1000);
} }
return 1;
}
Basic Electric Circuit
• Every circuit (electric or electronic) must have
at least a power source and a load.
• The simplest circuit is a light.
• Plug in the light, and it lights up.
• Unplug it, the light goes out.
• Electricity flows from the power source,
through the load (the light) and then back to
the power source.
Putting It Together
• Complete the sketch
(program) below.
• What output will be
generated by this program?
• What if the schematic were
changed? ➔
Blink Sketch
void setup( ) {
Connected to one
pinMode(13, OUTPUT); end of the circuit
Connected to
other end of the
} circuit
void loop( ) {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
4 LED Blink Sketch
void setup( ) { void loop( ) {
pinMode(1, OUTPUT); digitalWrite(1, HIGH);
pinMode(3, OUTPUT); delay (200);
pinMode(5, OUTPUT); digitalWrite(1, LOW);
pinMode(7, OUTPUT);
} digitalWrite(3, HIGH);
delay (200);
digitalWrite(3, LOW);

digitalWrite(5, HIGH);
delay (200);
digitalWrite(5, LOW);

digitalWrite(7, HIGH);
delay (200);
digitalWrite(7, LOW);
}
So What?
• Great. Blinking lights. Not impressed.
• Only covered output thus far.
• Can use analog inputs to detect a physical
phenomena.
Inputs
• Digital inputs will come to the Arduino as either
on or off (HIGH or LOW, respectively).
– HIGH is 5VDC.
– LOW is 0VDC.
• 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)
Analog Input
• A potentiometer (variable
resistor) is connected to
analog pin 0 to an Arduino.
• Values presented to pin 0
will vary depending upon
the resistance of the
potentiometer.
Analog Input-Application
• The variable resistor can be replaced with
a sensor.
• For example, a photo resistor.
– Depending upon the light level at the photo
resistor:
• Turn on a light
• Increase or decrease the brightness of an LED (or an
LED array)
• Most sensors are simply variable resistors,
but vary their resistance based on some
physical characteristic.
Sensors
1. Sensors can be both binary or a range.
2. Usually, sensors that measure a range
of values vary their resistance to reflect
their detection.
3. Arduinos can only sense voltages, not
resistances.
4. Sensors that only vary their resistances
require a circuit called a voltage divider
to provide the Arduino a voltage.
Common Sensors

• Dials on a radio are • Infrared sensor & light


simply potentiometers • Hall effect sensor and
• Temperature magnet
• Light • Ball tilt sensor (for
• Angle measuring orientation)
• Switches • Force
– did the user throw a
switch or push a button?
• Accelerometer
(measures motion and
tilt)
“Competitors”to the Arduino
• PIC controller
– Microcontroller programmed with C or assembler
• Alternatives to the Arduino line
– Pinguino – PIC controller
– MSP430 – Texas Instruments; $4.30
– Others: customs, Teensy, etc.
• Netduino
• Computers
– Raspberry Pi
– BeagleBones – TI; has computer and controller
Netduino
• Microcontroller and development tools created by
Microsoft to work with the .NET Micro Framework.
• VASTLY better development environment.
– visualmicro.com
– Other alternatives
• Differences
– Pins on a Netduino are 3.3V (not 5).
– Netduinos have a much faster processor.
– 60K of RAM (versus an Uno's 2K).
• Largely compatible with the Arduino, but it is not a drop-
in replacement (can fry it).
Raspberry Pi
• Low end computer, not a controller
• Uses Debian Linux
– Arch Linux ARM, Fedora, FreeBSD, Slackware…
• Programmed with Python
– BBC BASIC, C, Perl
• As it is a computer and not a controller, its role
in these projects is different.
• Hierarchy: computers control controllers,
controllers control hardware.
Shields
• Shields are circuit boards that plug into the
top of an Arduino.
• They extend the capabilities of an Arduino.
• Examples:
– Ethernet
– GPS
– Motor
– Prototype
• shieldlist.org
This semester: 12 meeting & 2 exam
1. Introduction Arduino (a demonstration video)
2. Instruction (arith., comp., logical, cond., loop)
3. Analog read
4. Analog write
5. Motor (DC/ Servo/ Stepper)
6. SPI/ I2C
7. Mid Test (UTS)
8. DHT11 temp./humidity
@meeting:
9. TCS32000 color sensor
1. Lecturing: 30 minute
10.RTC DS1307
2. Exercise: 20 minute
11.MPU 6050 Acc/Gyro
3. Assignment: 5 minute
12.Student presentation
4. Closing: 5 minute
13.Student presentation
14.Final test
Arduino Coding.

Stylize, edit, and animate your media


Data Types and operators
Integer: used with integer variables with value between 2147483647
and -2147483647.
Ex. int x=1200;

Character: used with single character, represent value from -127 to


128.
Ex. char c=‘r’;

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.
Ex. long u=199203;

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.
Ex. float num=1.291;
Statement and operators:
Statement represents a command, it ends with ;
Ex:
int x;
x=13;
Operators are symbols that used to indicate a specific
function:
- Math operators: [+,-,*,/,%,^]
- Logic operators: [==, !=, &&, ||]
- Comparison operators: [==, >, <, !=, <=, >=]
Syntax:
; Semicolon, {} curly braces,
//single line comment,
/*Multi-line comments*/
Statement and operators:
Compound Operators:
++ (increment)
-- (decrement)
+= (compound addition)
-= (compound subtraction)
*= (compound multiplication)
/= (compound division)
Control statements:
Switch case:
switch (var) {
case 1:
//do something when var equals 1
break;
case 2:
//do something when var equals 2
break;
default:
// if nothing else matches, do the default
}
Syntax
while while(condition)
{
// statement(s)
}

var = 0;
while(var < 200)
{
// do something repetitive 200 times
var++;
}
do...while Syntax:
do
{
// statement block
} while (condition);

Example Code:
do
{
delay(50); // wait for sensors to stabilize
x = readSensors(); // check the sensors
} while (x < 100);
Syntax
if...else if (condition)
{
//statement(s)
}
Example:

if (digitalRead(buttonPin) == LOW)
{
digitalWrite(ledPin, LOW);
}
if(condition)
if...else {
statements-1;

statement-N;
}
else if(condition2)
{
Statements;
}
Else{statements;}
for Syntax
for (condition)
{
//statement(s)
}

for (int i = 0; i < 3; i++)


{
Serial.print(".");
}
Input and output:
pinMode(pin,OUTPUT);
digitalRead(pin);
digitalWrite(pin,HIGH);
delay(time_ms);

v=analogRead(pin);
analogWrite(pin);//PWM.
This semester: 12 meeting & 2 exam
1. Introduction Arduino (a demonstration video)
2. Instruction (arith., comp., logical, cond., loop)
3. Analog input
4. Analog output
5. Motor (DC/ Servo/ Stepper)
6. SPI/ I2C
7. Mid Test (UTS)
8. DHT11 temp./humidity
@meeting:
9. TCS32000 color sensor
1. Lecturing: 30 minute
10.RTC DS1307
2. Exercise: 20 minute
11.MPU 6050 Acc/Gyro
3. Assignment: 5 minute
12.Student presentation
4. Closing: 5 minute
13.Student presentation
14.Final test
Analog input

Stylize, edit, and animate your media


Analog Input and Sensors
Reference Voltage (optional) • Six analog inputs:
A0, A1, A2, A3, A4, A5
• AREF = Reference voltage
(default = +5 V)
• 10 bit resolution:
– returns an integer from 0 to
1023
– result is proportional to the
pin voltage
• All voltages are measured
relative to GND

Note: If you need additional


Analog Inputs digital I/O, the analog pins can be
re-assigned for digital use:
pinMode(A0, OUTPUT);
Reading Analog Values
• value = analogRead(pin)
Reads the analog measurement on pin
Returns integer between 0 and 1023
• analogReference(type)
type can be:
– DEFAULT - the default analog reference of 5 volts (on
5V Arduino boards)
– INTERNAL – Built-in reference voltage (1.1 V)
– EXTERNAL – AREF input pin
Note: Do NOT use pinMode(A0, INPUT) unless you want to
use A0 for DIGITAL input.
Aside: Potentiometers
(variable resistors, rheostats)
Activity 5 – Volume Knob
• Connect the potentiometer from 5V to GND
• Use analogRead(A0) to measure the voltage on the center pin
• Set the LED blink rate depending on the reading
Activity 6 – Arduino
Thermometer

• Build a circuit and write a sketch to


read and report the temperature at
1 second intervals
Example: analogRead() display to 0-1023
int analogPin = 3;
// potentiometer wiper (middle terminal)
// connected to analog pin 3
// outside leads to ground and +5V
int val = 0; // variable to store the value read
void setup() {
Serial.begin(9600); // setup serial
}

void loop() {
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}
Example: analogRead() display to 0.0 - 5.0

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:


void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023)
// to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
Example: analogRead() and Control LED
const int LED = 13;
Int sensorValue;
void loop()
{
sensorValue = analogRead(A0)
// read input value and store it
// check whether the input is HIGH ( button
pressed )
if (sensorValue> 500) {
digitalWrite(LED, HIGH); // turn LED on
} else {
digitalWrite(LED, LOW); // turn LED off
}
}
This semester: 12 meeting & 2 exam
1. Introduction Arduino (a demonstration video)
2. Instruction (arith., comp., logical, cond., loop)
3. Analog input
4. Analog output
5. Motor (DC/ Servo/ Stepper)
6. SPI/ I2C
7. Mid Test (UTS)
8. DHT11 temp./humidity
@meeting:
9. TCS32000 color sensor
1. Lecturing: 30 minute
10.RTC DS1307
2. Exercise: 20 minute
11.MPU 6050 Acc/Gyro
3. Assignment: 5 minute
12.Student presentation
4. Closing: 5 minute
13.Student presentation
14.Final test
Analog output

Stylize, edit, and animate your media


analogWrite()
Syntax:
analogWrite(pin,value)

Description
1. Writes an analog value (PWM wave) to a pin.
2. An analog value ranges from 0 to 255.
3. In Arduino Uno/Nano microcontroller, Only pins 3, 5,
6, 9, 10, 11 can be used as analog output pins as
they have the ~ sign printed beside their pin
number.
4. The ~ sign means that the pin is PWM-enabled
PWM pin on NANO
PWM pin on MEGA16
Analog Output?

• Most microcontrollers have


only digital outputs
• Pulse-width Modulation:
Analog variables can be
represented by the duty-
cycle (or pulse-width) of a
digital signal
Pulse Width Modulation

• PWM, also
known as Pulse
Width
Modulation, is a
technique for
getting analog
results with
digital means.
PWM Duty Cycle
output voltage = (on_time / cycle_time) * 5V

Fixed cycle length; constant


number of cycles/sec
PMW Pins

• Command:
analogWrite(pin,value)

• value is duty cycle:


between 0 and 255

• Examples:
analogWrite(9, 128)
for a 50% duty cycle

analogWrite(11, 64)
for a 25% duty cycle
Image from Theory and Practice of Tangible User Interfaces at UC Berkley
PulseWidth Modulation (PWM)
PWM available on pins 3, 5, 6, 9, 10, 11
• analogWrite(pin,val)
set the PWM fraction:
– val = 0: always off
– val = 255: always on
• Remember to designate pin
for digital output:
pinMode(pin,OUTPUT);
(usually in setup)
• Default PWM frequency:
– 16 MHz / 215 = 488.28125 Hz
Note: the PWM frequency and
resolution can be changed by
re-configuring the timers
PWM LED Dimmer
• Use PWM to control the brightness of an LED
– connect LED to pin 3, 5, 6, 9, 10 or 11
– remember to use 220 Ω current-limiting resistor
• Set the brightness from the serial port, or
potentiometer

Useful:
• newValue = map(oldValue, a, b, c, d)
Converts/maps a number in the range (a:b) to a new number in
the range (c:d)
Example:
– newValue = map(oldValue,0,1023,0,255);
ADC PWM

const int pwm = 2 ; //naming pin 2 as ‘pwm’ variable


const int adc = 0 ; //naming pin 0 of analog input side as ‘adc’
void setup() {
pinMode(pwm,OUTPUT) ; //setting pin 2 as output
}
void loop() {
int adc = analogRead(0) ; //reading analog voltage and storing it in an integer
adc = map(adc, 0, 1023, 0, 255); /* ----------map funtion------------the above funtion
//scales the output of adc, which is 10 bit and gives values btw 0 to 1023, in values
btw
//0 to 255 form analogWrite funtion which only receives values btw this range */
analogWrite(pwm,adc) ;
}
This semester: 12 meeting & 2 exam
1. Introduction Arduino (a demonstration video)
2. Instruction (arith., comp., logical, cond., loop)
3. Analog input
4. Analog output
5. Motor (DC/ Servo/ Stepper)
6. SPI/ I2C
7. Mid Test (UTS)
8. DHT11 temp./humidity
@meeting:
9. TCS32000 color sensor
1. Lecturing: 30 minute
10.RTC DS1307
2. Exercise: 20 minute
11.MPU 6050 Acc/Gyro
3. Assignment: 5 minute
12.Student presentation
4. Closing: 5 minute
13.Student presentation
14.Final test
Motor
Servomotors

• Standard servo:
– PWM duty cycle controls direction:
– 0% duty cycle → 0 degrees
– 100% duty cycle → 180 degrees
• Continuous-rotation servo:
– duty cycle sets speed and/or direction
Activity 9 – Servomotor Control

• Build a program that turns a servomotor


from 0 to 180 degrees, based on
potentiometer reading
• Report setting to the serial monitor
Generates a Pulse Width for a servo
Build a connection to arduino
Generates a Pulse Width using delay

#define servoPin 9
void setup() {
pinMode(servoPin, OUTPUT);
}
void loop() {
// A pulse each 20ms
digitalWrite(servoPin, HIGH);
delayMicroseconds(1500); // ON TIME
digitalWrite(servoPin, LOW);
delayMicroseconds(18500); // OFF TIME
}
A listing program using SERVO Library
#include <Servo.h>
int servoPin = 3;
Servo Servo1;
void setup() {
Servo1.attach(servoPin);
}
void loop(){
Servo1.write(0); // Make servo go to 0 degrees
delay(1000);
Servo1.write(90); // Make servo go to 90 degrees
delay(1000);
Servo1.write(180); // Make servo go to 180 degrees
delay(1000);
}
Driving a servo using ANALOG (ADC)
#include <Stepper.h>
const int stepsPerRevolution = 200;
// / change this to fit the number of steps per revolution
// for your motor
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0; // number of steps the motor has taken
void setup() {
// nothing to do inside the setup
}
void loop() {
int sensorReading = analogRead(A0);
// map it to a range from 0 to 100:
int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
// set the motor speed:
if (motorSpeed > 0) {
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(stepsPerRevolution / 100);
}
}
This semester: 12 meeting & 2 exam
1. Introduction Arduino (a demonstration video)
2. Instruction (arith., comp., logical, cond., loop)
3. Analog input
4. Analog output
5. Motor (DC/ Servo/ Stepper)
6. SPI/ I2C
7. Mid Test (UTS)
8. DHT11 temp./humidity
@meeting:
9. TCS32000 color sensor
1. Lecturing: 30 minute
10.RTC DS1307
2. Exercise: 20 minute
11.MPU 6050 Acc/Gyro
3. Assignment: 5 minute
12.Student presentation
4. Closing: 5 minute
13.Student presentation
14.Final test
SPI/ I2C
Communication: I2C, SPI
• I2C (Inter-Integrated Circuit)
– Developed by Phillips
– Speed = 100 kHz, 400 kHz, and 3.4 MHz (not
supported by Arduino)
– Two bi-directional lines: SDA, SCL
– Multiple slaves can share same bus
• SPI (Serial Peripheral Interface Bus)
– Speed = 1-100 MHz (clock/device limited)
– Four-wire bus: SCLK, MOSI, MISO, SS
– Multiple slaves can share same bus
(but each needs a dedicated SS, slave select)
Connecting Multiple Devices
(I2C and SPI)

Master with three SPI slaves:

Master (µC) with three I2C slaves:


SPI and I2C on the Arduino

SCK (13) MISO (12) MOSI (11) SS (10)

SPI pins:
• SCK = serial clock
• MISO = master in, slave out
• MOSI = master out slave in
• SS = slave select
I2C pins:
• SDA = data line
• SCL = clock line
SDA (A4) SCL (A5)
Basic Arduino I2C Commands
COMMAND EXPLANATION
Wire.begin() Join the I2C bus as master (usually
invoked in setup)
Wire.beginTransmission(address) Begin communicating to a slave
device
Wire.write(byte) Write one byte to I2C bus (after
request)
Wire.endTransmission(address) End transmission to slave device

Note: you must include the Wire library: Note: pinMode() not needed
#include <Wire.h> for I2C on pins A4 and A5
Example: MCP4725 12-bit DAC
MCP4725 write command (taken from data sheet)

7-bit I2C address command power down mode data bits (MSB → LSB)
(1100000) (010) (00)
Note: binary numbers are preceded by B:
B1100000 = 96

Arduino program segment: data >> 4: shift bits left by four positions

Wire.beginTransmission(B1100000); // Byte 1 (Initiate communication)


Wire.write(B01000000); // Byte 2 (command and power down mode)
Wire.write(data >> 4); // Byte 3 (send bits D11..D4)
Wire.write((data & B00001111) << 4); // Byte 4 (send bits D3..D0)
Wire.endTransmission();

Remember: you must include the Wire library at the top:


#include <Wire.h>
and you must also use Wire.begin() in setup
Additional I2C Commands
COMMAND EXPLANATION
Wire.begin() Join the I2C bus as master (usually invoked
in setup)
Wire.begin(address) Join the I2C bus as slave, with address
specified (usually invoked in setup)
Wire.beginTransmission(address) Begin communicating to a slave device
Wire.write(byte) Write one byte to I2C bus (after request)
Wire.write(bytes,length) Write length bytes to I2C bus
Wire.endTransmission(address) End transmission to slave device
Wire.requestFrom(address, quantity) Request bytes (quantity) from slave
Wire.requestFrom(address, quantity, stop)
Wire.available() The number of bytes available for reading
Wire.read() Reads a byte that was transmitted from a
slave. (Preceded by Wire.requestFrom)

Note: you must include the Wire library: Note: pinMode() not needed
#include <Wire.h> for I2C on pins A4 and A5
Activity 12: Sawtooth Wave
• Program the MCP4725 DAC to produce a
sawtooth (ramp) wave:
– What is the frequency of the sawtooth wave?
– Can you make f = 100 Hz?
MCP4725
Note: the I2C bus requires pull-
breakout
up resistors on SCL and SDA
board: (provided on the board)

http://www.sparkfun.com/
Basic Arduino SPI Commands
COMMAND EXPLANATION
SPI.begin() Initializes the SPI bus, setting SCK,
MOSI, and SS to outputs, pulling
SCK and MOSI low and SS high.
byteIn = SPI.transfer(byteOut) Transfer one byte (both send and
receive) returns the received byte

Note: you must include the SPI library:


#include <SPI.h>

Note: pinMode() not needed. It is


automatically configured in SPI.begin()
Additional Arduino SPI
Commands
COMMAND EXPLANATION
SPI.begin() Initializes the SPI bus, setting SCK, MOSI, and SS to
outputs, pulling SCK and MOSI low and SS high.
SPI.end() Disables the SPI bus (leaving pin modes unchanged) – in
case you need to use pins 10-13 again
SPI.setBitOrder(order) Set bit order for SPI
order = {LSBFIRST, MSBFIRST}
SPI.setClockDivider(divider) Set the SPI clock divider
divider = {2, 4, 8, 16, 32, 64, 128}
SPI clock speed = 16 MHz/divider
SPI.setDataMode(mode) Set the SPI data mode
mode = {SPI_MODE0, SPI_MODE1, SPI_MODE2, SPI_MODE3}
SPI.transfer(byte) Transfer one byte (both send and receive)
returns the received byte

Note: you must include the SPI library: Note: pinMode() not needed
#include <SPI.h>
Example: AD5206 Digital
Potentiometer
Functional block diagram:
Features:
• six independent, 3-
wiper potentiometers
• 8-bit precision
(256 possible levels)
• Available in 10kΩ,
50kΩ and 100kΩ
• Programmed
through SPI interface
AD5206 Write Sequence
Note: same as MOSI
(master out slave in)

Note: same as SS
(slave select)

Arduino program segment:


SPI.begin(); // initialize SPI (in setup)
...
digitalWrite(SS,LOW); // hold SS pin low to select chip
SPI.transfer(potnumber); // determine which pot (0..5)
SPI.transfer(wipervalue); // transfer 8‐bit wiper setting
digitalWrite(SS,HIGH); // de‐select the chip
Activity 13: Programmable
Voltage Divider
• Use the AD5206 to build a programmable
voltage divider
• Allow the user to set the resistance from
the serial port
• Measure resistance with an Ohm meter,
or using analogRead()
AD5206: Summary of Pins and
Commands
SCK (13) MISO (12) MOSI (11) SS (10)

Remember: SPI.begin() needed in setup() and #include <SPI.h>

digitalWrite(SS,LOW); // hold SS pin low to select chip


SPI.transfer(potnumber); // determine which pot (0..5)
SPI.transfer(wipervalue); // transfer 8‐bit wiper setting
digitalWrite(SS,HIGH); // de‐select the chip
Serial Communication
Basics of serial communication

Parallel: expensive - short distance – fast – no modulation


Serial :cheaper– long (two different cities by modem)-slow
Basics of serial communication
PANJANG KABEL KOM. RS232
1. Standart RS232 menyarankan batasan panjang kabel 50
feet ( 1 m = 3,3 feet )
2. Sesungguhnya kita dapat mengabaikan standard ini, karena
kabel dapat lebih panjang dari 10.000 feet pada baudrate
sampai 19200 bps, jika kita menggunakan kabel yang
berkualitas dan terlindungi.
Baudrate Shielded Cable Length Unshielded Cable Length
BPS (feet) (feet)
9600 250 100
4800 500 250
2400 2000 500
1200 3000 500
300 4000 1000
110 5000 1000
98
The Power of Serial Comm. RS232
KOMUNIKASI SINKRON
1. Dua buah divais diinisialisasi atau disinkronisasi menggunakan clock
yang sama dan secara kontinu dapat mengirimkan atau menerima
karakter untuk tetap sinkron.
2. Komunikasi sinkron mempunyai kecepatan yang lebih tinggi bila
dibandingkan dengan asinkron, karena tidak ada penambahan bit, untuk
menandai permulaan dan akhiran byte data.
3. Port Serial pada PC adalah asinkron divais, sehingga hanya support
untuk komunikasi serial asinkron
DATA D0 D1 D2 D3 D4 D5 D6 D7

CLOCK

99
KOMUNIKASI ASINKRON
1. Asinkron berarti tanpa sinkronisasi, sehingga tidak diperlukan
pengiriman sinyal clock.
2. Akan tetapi, pada setiap awalan dan akhiran harus ditandai dengan bit
start dan bit stop.
3. Start bit menunjukkan, bahwa data akan segera dikirim atau diterima,
dan bit stop menyatakan akhiran dari sinyal.
4. Keperluan penambahan pengiriman dua bit ini akan menyebabkan
komunikasi asinkron akan lebih lambat bila dibandingkan dengan
komunikasi sinkron.
5. Pada jalur asinkron, kondisi idle dinyatakan sebagai nilai ‘1’ ( yang juga
disebut sebagai keadaan mark )

100
Asynchronous Transmission Format

• Bit Types
–Start bit
–Data bits
–Parity bit
–Stop bits

101
Definitions

• Start Bit
– Signals the beginning of a word
– Is normally a ‚0‘ and is detected as a transition from high
to low
• Data Bits
– The actual data, which should be transmitted
– Sender and receiver have to agree on the number of data
bits (usually 8)
– Always the least significant bit will be send first

102
Definitions cont

• Parity Bit
– An error check
– Odd or even parity
• Odd parity means the sum of the 1‘s will be odd
• Even parity means the sum of the 1‘s will be even
• You count all bits including the parity bit
– Disadvantage: If two bytes altered by noise, an error
will not be detected by the parity check

103
Definitions cont

• Stop Bits
– These bits mark the end of a data word
– Is usually high (1)

104
Asynchronous Data Transmission

• Example 1:
– Hex# 4A16 is to be sent with one start bit, even parity, 8-
bit data length and two stop bits
– 4A16 = 0100 10102

Start Bit Data Bit 0 Data Bit 1 Data Bit 2 Data Bit 3 Data Bit 4 Data Bit 5 Data Bit 6 Data Bit 7 Parity Bit Stop Bit Stop Bit

0 0 1 0 1 0 0 1 0 1 1 1

105
Asynchronous Data Transmission

• Example 2:
– Hex# B416 is to be sent with one start bit, even parity, 8-
bit data length and two stop bits
– B416 = 1011 01002

Start Bit Data Bit 0 Data Bit 1 Data Bit 2 Data Bit 3 Data Bit 4 Data Bit 5 Data Bit 6 Data Bit 7 Parity Bit Stop Bit Stop Bit

0 0 0 1 0 1 1 0 1 0 1 1

106
Asynchronous Data Transmission

• Example 3:
– Hex# B416 is to be sent with one start bit, odd parity, 8-
bit data length and two stop bits
– B416 = 1011

Start Bit Data Bit 0 Data Bit 1 Data Bit 2 Data Bit 3 Data Bit 4 Data Bit 5 Data Bit 6 Data Bit 7 Parity Bit Stop Bit Stop Bit

0 0 0 1 0 1 1 0 1 1 1 1

107
Baud Rate vs. Bit Rate

• Definition Baud Rate:


– Number of changing states per second
– Includes start, data, parity and stop bits
• Definition Bit Rate:
– Number of data bits transmitted per second

Baud Rate > Bit Rate

108
Baud Rate Calculations

• Example:
– Consider baud rate: 4800 baud
– 12 bits/word = 1 start bit + 8 data bits + 1 parity bit + 2
stop bits

– Bit time = 1/(baud rate) = 1/4800baud = 0.208ms/bit


– Word time = (12 bits)*(bit time) = 2.5ms
– Word rate = 1/(word time) = 400 words/s
– Bit rate = (word rate)*(8 data bits) = 3200 bits/s

109

You might also like